package com.bassbooster.soundeffects.equalizer.view

import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.PixelFormat
import android.os.IBinder
import android.util.Log
import android.view.*
import android.view.WindowManager.LayoutParams
import android.widget.FrameLayout
import com.bassbooster.equalizer.R
import com.bassbooster.soundeffects.equalizer.data.model.ColorEdgeModel
import com.bassbooster.soundeffects.equalizer.event.ServiceHideNavigationBarEvent

import com.bassbooster.soundeffects.equalizer.view.activity.edgelighting.customview.ImageBorderView2
import org.greenrobot.eventbus.EventBus

class MainService : Service() {

    private lateinit var windowManager: WindowManager
    private var floatyView: View? = null

    private val listShape: ArrayList<Int> = arrayListOf(
        R.drawable.ic_ess,R.drawable.ic_fire,
        R.drawable.icon_record,R.drawable.icon_stop,R.drawable.ic_play,
        R.drawable.icon_record,R.drawable.icon_stop,R.drawable.ic_play)

    val listColor: ArrayList<ColorEdgeModel> = arrayListOf(
        ColorEdgeModel(R.drawable.ic_rectangle_red,"#EE2929"),
        ColorEdgeModel(R.drawable.ic_rectangle_yel,"#EAB93D"),
        ColorEdgeModel(R.drawable.ic_rectangle_blue,"#19E73A"),
        ColorEdgeModel(R.drawable.ic_rectangle_blues,"#1188DD"),
        ColorEdgeModel(R.drawable.ic_rectangle_t,"#CE1EEB")
        )
    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        EventBus.getDefault().post(ServiceHideNavigationBarEvent(true))
        windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val durationTop = intent?.getFloatExtra("changeDurationTop",0f) ?: 0f
        val durationBottom = intent?.getFloatExtra("changeDurationBottom",0f) ?: 0f
        val with = intent?.getIntExtra("changeWith",0) ?: 0
        val duration = intent?.getIntExtra("changeDuration",0) ?: 0
        val shape = intent?.getIntExtra("createBitmapByShape",0) ?:0
        val color = intent?.getStringExtra("changeColor")
        addOverlayView()
        floatyView?.findViewById<ImageBorderView2>(R.id.mImageBorder)?.apply {
            if (durationTop != 0f) {
                changeDurationTop(durationTop,durationTop)
            }
            if (durationBottom != 0f) {
                changeDurationBottom(durationBottom,durationBottom)
            }
            if (with != 0) {
                changeScaleFactor(with)
            }
            if (duration != 0) {
                changeDuration(duration)
            }
            if (shape != 0) {
                createBitmapByShape(shape)
            }
            if (color != null) {
                changeColor(Color.parseColor(color))
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }

//    override fun onCreate() {
//        super.onCreate()
//

//    }

    private fun addOverlayView() {

        val params: LayoutParams
        val layoutParamsType: Int = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            @Suppress("DEPRECATION")
            LayoutParams.TYPE_PHONE
        }

        // 0
        // FLAG_NOT_TOUCHABLE
        params = LayoutParams(
            LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT,
            layoutParamsType,
            LayoutParams.TYPE_WALLPAPER,
            PixelFormat.TRANSLUCENT)

        params.gravity = Gravity.CENTER or Gravity.START
        params.x = 0
        params.y = 0

        val interceptorLayout = object : FrameLayout(this) {

            override fun dispatchKeyEvent(event: KeyEvent): Boolean {

                // Only fire on the ACTION_DOWN event, or you'll get two events (one for _DOWN, one for _UP)
                if (event.action == KeyEvent.ACTION_DOWN) {

                    // Check if the HOME button is pressed
                    if (event.keyCode == KeyEvent.KEYCODE_BACK) {
                        Log.v(TAG, "BACK Button Pressed")
//                        val intent = packageManager.getLaunchIntentForPackage(applicationContext.packageName)
//                        intent?.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
//                        startActivity(intent)
//                        EventBus.getDefault()
//                            .post(ServiceEvent(true))
                        // As we've taken action, we'll return true to prevent other apps from consuming the event as well
                        return true
                    }
                }

                if (event.action == KeyEvent.KEYCODE_BACK){
                    Log.d("qqq", "dispatchKeyEvent: "+"dfdsf")
                }
                // Otherwise don't intercept the event
                return super.dispatchKeyEvent(event)
            }
        }

        val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

        floatyView = inflater.inflate(R.layout.floating_view, interceptorLayout)
        floatyView?.let {
            windowManager.addView(floatyView, params)
        } ?: run {
            Log.e(TAG, "Layout Inflater Service is null; can't inflate and display R.layout.floating_view")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        floatyView?.let {
            windowManager.removeView(it)
            floatyView = null
        }
    }

    companion object {
        private val TAG = MainService::class.java.simpleName
    }
}