package com.test.questionnairesdk.library

import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.PixelFormat
import android.os.Build
import android.os.IBinder
import android.view.*
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.app.NotificationCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.test.questionnairesdk.R

class HUD : Service() {
    var view: View? = null
    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    @SuppressLint("RtlHardcoded")
    override fun onCreate() {
        super.onCreate()
        if (Build.VERSION.SDK_INT >= 26) {
            val CHANNEL_ID = "my_channel_01"
            val channel = NotificationChannel(
                CHANNEL_ID,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(
                channel
            )
            val notification = NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("")
                .setContentText("").build()
            startForeground(1, notification)
        }
        Toast.makeText(baseContext, "onCreate", Toast.LENGTH_LONG).show()
        view = LayoutInflater.from(this).inflate(R.layout.record_dialog, null)
        val actionButton = view?.findViewById<Button>(R.id.record_dialog_delete)
        val stopButton = view?.findViewById<Button>(R.id.record_dialog_stop_recording)
        val pointerButton = view?.findViewById<View>(R.id.record_dialog_pointer)
        val webView = view?.findViewById<WebView>(R.id.scratchpad_webview)
        webView?.settings?.setAppCacheEnabled(true)
        webView?.settings?.javaScriptEnabled = true
        webView?.settings?.domStorageEnabled = true
        webView?.settings?.setAppCacheEnabled(true)
        webView?.settings?.loadsImagesAutomatically = true
        webView?.settings?.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
        webView?.loadUrl("${RetrofitNetworking.ASKRIBE_CONSUMER_BASE_URL}/mobile-overlay")
        webView?.setBackgroundColor(Color.TRANSPARENT)
        webView?.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null)
        var LAYOUT_FLAG = 0
        LAYOUT_FLAG = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            WindowManager.LayoutParams.TYPE_PHONE
        }
        val wm = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        webView?.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                webView?.setBackgroundColor(Color.TRANSPARENT)
                webView?.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null)
            }
        }
        // TODO: Should be WRAP_CONTENT for clicks to work properly
        val wrapContentParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            LAYOUT_FLAG,
            WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                    or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    or WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
            PixelFormat.TRANSLUCENT
        )

        val fullScreenParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            LAYOUT_FLAG,
            WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                    or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    or WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
            PixelFormat.TRANSLUCENT
        )

        actionButton?.setOnClickListener { actionButtonView: View? ->
            if (webView?.visibility == View.GONE) {
                webView.visibility = View.VISIBLE
                wm.updateViewLayout(view, fullScreenParams)
                actionButton.text = "Stop Annotation"
            } else {
                webView?.visibility = View.GONE
                wm.updateViewLayout(view, wrapContentParams)
                actionButton.text = "Start Annotation"
            }
        }

        stopButton?.setOnClickListener {
            val intent = Intent("fashtag-screen-record-stopped")
            intent.putExtra("record", "STOPPED")
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
            stopSelf()
        }

        view?.setOnTouchListener { view, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    val layoutParams =
                        (pointerButton?.layoutParams as? ConstraintLayout.LayoutParams)
                    layoutParams?.leftMargin = event.rawX.toInt() //- (view.width / 2)
                    layoutParams?.topMargin = event.rawY.toInt() //- view.height
                    pointerButton?.layoutParams = layoutParams
                }
            }
            false
        }
        wrapContentParams.gravity = Gravity.RIGHT or Gravity.TOP
        wrapContentParams.title = "Load Average"
        wm.addView(view, wrapContentParams)
    }

    fun onTouchEvent(event: MotionEvent?): Boolean { // ATTENTION: GET THE X,Y OF EVENT FROM THE PARAMETER
// THEN CHECK IF THAT IS INSIDE YOUR DESIRED AREA
        return true
    }

    override fun onDestroy() {
        val intent = Intent("fashtag-screen-record-stopped")
        intent.putExtra("record", "STOPPED")
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
        super.onDestroy()
        Toast.makeText(baseContext, "onDestroy", Toast.LENGTH_LONG).show()
        if (view != null) {
            (getSystemService(Context.WINDOW_SERVICE) as WindowManager).removeView(view)
            view = null
        }
    }
}