package com.lemonhc.mplus.mcare_plus.activity

import android.Manifest
import android.annotation.TargetApi
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.core.content.ContextCompat
import android.telephony.TelephonyManager
import android.view.KeyEvent
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.webkit.JsResult
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.ImageButton
import androidx.appcompat.app.AppCompatActivity
import com.lemonhc.mplus.MPlusConstants.IS_DEBUG_MODE
import com.lemonhc.mplus.framework.util.kotlinExtension.isCaptureFlag
import com.lemonhc.mplus.mcare_plus.R
import com.lemonhc.mplus.mcare_plus.activity.webView.MCareWebExtraPopupViewClient
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.error
import java.util.*

class MPlusPopupActivity: AppCompatActivity() {
    private var backBtn: ImageButton? = null
    private var forwardBtn: ImageButton? = null
    private var refreshBtn: ImageButton? = null
    private var closeBtn: ImageButton? = null
    private var webView: WebView? = null
    private var context: Context = this

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (!isCaptureFlag) {
            window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
        }

        this.requestWindowFeature(Window.FEATURE_NO_TITLE)

        MainActivity.isVisibleExWebView = true
        this.setContentView(R.layout.activity_mcare__plus__popup).run {
            webView = findViewById(R.id.webExtraPopupView)
            backBtn = findViewById(R.id.btn_back)
            closeBtn = findViewById(R.id.btn_close)
            forwardBtn = findViewById(R.id.btn_forward)
            refreshBtn = findViewById(R.id.btn_refresh)
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(IS_DEBUG_MODE)
        }

        initComponent(null, null)
        intent.getStringExtra("Url").let {
            AnkoLogger<String>().error { it }
            webView?.loadUrl(it)
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_HOME -> return true
            KeyEvent.KEYCODE_BACK -> {
                if (this.webView != null) {
                    if (this.webView!!.canGoBack()) {
                        this.webView!!.goBack()
                    } else {
                        this.closeAction("")
                    }
                }
                return true
            }
            KeyEvent.KEYCODE_MENU -> return true
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * 객체 초기화
     * @param paymentReqUrl 요청 보낼 URL
     */
    private fun initComponent(paymentReqUrl: String?, callBackFnName: String?) {
        paymentReqUrl?.let {
            webView?.webViewClient = MCareWebExtraPopupViewClient(this)
        }.let {
            webView?.webViewClient = MCareWebExtraPopupViewClient(this)
        }

        backBtn?.setOnClickListener { _ ->
            if (webView?.canGoBack() == true) webView?.goBack()
        }
        forwardBtn?.setOnClickListener { _ ->
            if (webView?.canGoForward() == true) webView?.goForward()
        }
        refreshBtn?.setOnClickListener { _ ->
            webView?.reload()
        }
        closeBtn?.setOnClickListener(closeActionListener(callBackFnName))

        webView?.settings?.apply {
            javaScriptEnabled = true
            javaScriptCanOpenWindowsAutomatically = true
            saveFormData = true
            domStorageEnabled = true
            cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
            setSupportMultipleWindows(false)
            userAgentString = userAgentString + " uuid:" + getDeviceUUID()
            builtInZoomControls = true
            setSupportZoom(true)
            mediaPlaybackRequiresUserGesture = false
            loadWithOverviewMode = true
            useWideViewPort = true
            textZoom = 100
        }

        /**
         * 인증창에서 취소가 발생할때 호출된다고 한다.
         */
        webView?.webChromeClient = object : WebChromeClient() {
            override fun onJsAlert(view: WebView, url: String, message: String, result: JsResult): Boolean {
                val dlg = AlertDialog.Builder(this@MPlusPopupActivity)
                dlg.setTitle("")
                dlg.setMessage(message)
                dlg.setCancelable(false)
                dlg.create().show()
                return true
            }
            override fun onCloseWindow(webView: WebView) {
                super.onCloseWindow(webView)
                // 결제요청 페이지 URL을 기입하라고 되어 있음
                if (paymentReqUrl != null) {
                    webView.postUrl(paymentReqUrl, null)
                }
            }
        }
    }

    private fun closeActionListener(s: String?): View.OnClickListener {
        return View.OnClickListener {
            this.closeAction(s)
        }
    }

    private fun closeAction(s: String?) {
        val configuration: Configuration = this.resources.configuration
        val orientation: Int = configuration.orientation
        val intent = Intent()
        intent.putExtra("callbackFn", s)
        intent.putExtra("orientation", orientation)
        this.setResult(Activity.RESULT_OK, intent)
        this.finish()
    }

    @TargetApi(Build.VERSION_CODES.O)
    private fun getDeviceUUID(): String {
        var id: String? = null
        val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                id = tm.imei
            } else {
                id = tm.deviceId
            }
        }
        if (id == null || "9774d56d682e549c" == id) {
            // android_id는 공장초기화하면 지워지는 값임
            id = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
            if (id == null) {
                id = UUID.fromString(tm.line1Number).toString()
            }
        }
        return id
    }

}