package com.assimilate.alltrans.allservice

import android.app.Activity
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import androidx.core.app.NotificationCompat
import com.assimilate.alltrans.R
import com.assimilate.alltrans.common.FirebaseAnalyticsHelper
import com.assimilate.alltrans.common.ScreenCaptureManager
import com.assimilate.alltrans.curview.ControlView
import com.assimilate.alltrans.curview.CopyTextView
import com.assimilate.alltrans.curview.FloatingView
import com.assimilate.alltrans.curview.GlobalView
import com.assimilate.alltrans.curview.LanguageSelectorView
import com.assimilate.alltrans.curview.SelectionView

class SusService : Service() {

    private val mpResultCode = "mpResultCode"
    private val mpData = "mpData"

    private lateinit var languageSelectorView: LanguageSelectorView

    private lateinit var screenCaptureManager: ScreenCaptureManager
    private lateinit var floatingView: FloatingView
    private lateinit var controlView: ControlView
    private lateinit var globalView: GlobalView
    private lateinit var selectionView: SelectionView
    private lateinit var copyTextView: CopyTextView

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent == null) {
            return START_NOT_STICKY
        }

        val resultCode = intent.getIntExtra(mpResultCode, Activity.RESULT_CANCELED)
        val data = intent.getParcelableExtra<Intent>(mpData)

        if (resultCode == Activity.RESULT_OK && data != null) {
            screenCaptureManager = ScreenCaptureManager(this)
            screenCaptureManager.setProjectionParams(resultCode, data)
            screenCaptureManager.startProjection()
            addFloatingView()

        } else {
            Log.e("SusService", "Intent or data is null")
        }

        return START_NOT_STICKY
    }

    override fun onCreate() {
        super.onCreate()
        startForeground(1, createNotification())
    }

    private fun addFloatingView() {
        floatingView = FloatingView(this)
        floatingView.attachToWindow()
        floatingView.setOnMovePointListener(object : FloatingView.OnMovePointListener {
            override fun onMovePoint() {
                Log.d("SusService_f", "FloatingView moved")
                floatingView.setImageReader(screenCaptureManager.getImageReader())
            }
        })
        floatingView.setOnClickListener(object : FloatingView.OnClickListener {
            override fun onClick() {
                Log.d("SusService_f", "FloatingView clicked")
                addControlView()
                FirebaseAnalyticsHelper.hoverScreenClickEvent()
            }
        })
    }

    private fun addControlView() {
        controlView = ControlView(this)

        controlView.setControlViewListener(object : ControlView.ControlViewListener {
            override fun onGlobalClick() {
                globalView = GlobalView(this@SusService)
                Handler(Looper.getMainLooper()).postDelayed({
                    globalView.addGlobalView(screenCaptureManager.getImageReader())
                }, 333)

                FirebaseAnalyticsHelper.hoverScreenGlobalEvent()
            }

            override fun onCopyClick() {
                copyTextView = CopyTextView(this@SusService)
                copyTextView.addView(screenCaptureManager.getImageReader())
            }

            override fun onDistrictClick() {
                selectionView = SelectionView(this@SusService)
                selectionView.addSelectionView(screenCaptureManager.getImageReader())
                FirebaseAnalyticsHelper.hoverScreenDistrictEvent()
            }

            override fun onChangeLan() {
                languageSelectorView = LanguageSelectorView(this@SusService)
                languageSelectorView.createFloatingView()
            }
        })

        controlView.addControlView()
    }

    private fun createNotification(): Notification {
        Log.d("SusService", "Creating notification")
        val notificationChannelId = "FOREGROUND_SERVICE_CHANNEL"

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelName = "Foreground Service Channel"
            val chan = NotificationChannel(
                notificationChannelId,
                channelName,
                NotificationManager.IMPORTANCE_NONE
            )
            val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            manager.createNotificationChannel(chan)
        }

        val builder = NotificationCompat.Builder(this, notificationChannelId)
            .setContentTitle("Screen Translation Service")
            .setContentText("Screen translation is running...")
            .setSmallIcon(R.drawable.ic_close)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setCategory(Notification.CATEGORY_SERVICE)

        return builder.build()
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d("SusService", "Service onDestroy")

        if (::controlView.isInitialized) {
            controlView.removeControlView()
        }

        if (::floatingView.isInitialized) {
            floatingView.detachFromWindow()
        }

        if (::selectionView.isInitialized) {
            selectionView.removeSelectionView()
        }

        if (::screenCaptureManager.isInitialized) {
            screenCaptureManager.stopProjection()
        }
        if (::copyTextView.isInitialized) {
            copyTextView.removeView()
        }
        if (::globalView.isInitialized) {
            globalView.removeGlobalView()
        }

    }

}
