package com.seatel.mobilehall.ui.home.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import com.seatel.mobilehall.R
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.customview.ErrorHandleView
import kotlinx.android.synthetic.main.activity_wing_payment.*


class WingPaymentActivity : BaseActivity() {
    private lateinit var mUrlPay: String
    private var mAmount: Double = 0.0
    private var isAbleBack: Boolean = false
    private var isShowValentineDayPromotion = false

    private val mWebViewClient = object : WebViewClient() {

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            if (url != null && view != null) {
            }
        }

        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            showHideLoading(false)

        }

        override fun onReceivedError(
            view: WebView, request: WebResourceRequest, error: WebResourceError
        ) {
            super.onReceivedError(view, request, error)
            closeWingPaymentWithError()
        }

        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            Log.d("TAG::>>>", "shouldOverrideUrlLoading: $url ${Uri.parse(url).host} $view")
            if (Uri.parse(url).host == "dev.yes.com.kh" || Uri.parse(url).host == "sdk-uat.wingmoney.com") {
                // This is your website, so don't override. Let your WebView load
                // the page.
                return false
            }

            val mUrl = url!!.replace("wingbankuat", "wingbankapp")
            Log.d("TAG::>>>", "shouldOverrideUrlLoading: $mUrl")

            // Otherwise, the link isn't for a page on your site, so launch another
            // Activity that handles URLs.
            Intent(Intent.ACTION_VIEW, Uri.parse(mUrl)).apply {
                startActivity(this)
                finish()
            }
            return true
        }

        /*   override fun shouldOverrideUrlLoading(
               view: WebView?, request: WebResourceRequest?
           ): Boolean {


               val url = request?.url.toString()
               val host = request?.url?.host.toString()
               val scheme = request?.url?.scheme.toString()
               Log.d("TAG::>>>", "shouldInterceptRequest: $url $host $scheme")
               if (url.contains("wingbankapp")) {
                   openDeeplink(url)
                   return false
               }

               Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply {
                   startActivity(this)
               }

              *//* if (host.equals("play.google.com")) {
                gotoPlayStore()
            }*//*

             *//*if (isPaywayDeeplink(host, scheme)) {
                 openDeeplink(url)
                 return false
             }*//*

            return isOverrideUrlLoading(view, request)
        }
*/

    }

    open fun isOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
        return false
    }

    open fun isOverrideUrlLoading(view: WebView?, url: String?): Boolean {
        return false
    }

    private fun closeWingPaymentWithError() {

        showHideLoading(false)/* SeatelAlertDialog.with(this, getString(R.string.message_wing_error)).setCancelable(true)
             .setPositiveButton(getString(R.string.yes)) { _, _ ->
                 exitWingPayment(false)
             }.show()*/
    }

    private fun closePaymentProcress() {
        if (web_view_wing.canGoBack()) {
            web_view_wing.goBack()
        } else {
            showHideLoading(false)
            SeatelAlertDialog.with(this, getString(R.string.cancel_process_payment))
                .setCancelable(true).setPositiveButton(getString(R.string.yes)) { _, _ ->
                    exitWingPayment(false)
                }.setNegativeButton(getString(R.string.cancel)) { dailog, _ ->
                    dailog.dismiss()
                }.show()
        }
    }

    override fun isDisplayBackgroundBlur(): Boolean {
        return false
    }

    override fun isDisplayToolbar(): Boolean {
        return false
    }

    override fun isStatusBarColorDark(): Boolean {
        return true
    }


    private fun openDeeplink(url: String) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.data = Uri.parse(url)
        val packageManager = this.packageManager
        val resolvedActivities = packageManager.queryIntentActivities(intent, 0)
        if (resolvedActivities.size > 0) startActivity(intent)
        else gotoPlayStore()

    }


    private fun gotoPlayStore() {
        try {
            startActivity(
                Intent(
                    Intent.ACTION_VIEW, Uri.parse("market://details?id=com.wingmoney.wingpay")
                )
            )
        } catch (obj: android.content.ActivityNotFoundException) {
            startActivity(
                Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("https://play.google.com/store/apps/details?id=com.wingmoney.wingpay")
                )
            )
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_wing_payment)
        activityEnterFadeInAnimation()
        showHideLoading(true)
        init()
    }

    private fun showHideLoading(isShow: Boolean) {
        if (isShow) {
            error_view.visibility = View.VISIBLE
            error_view.setViewMode(ErrorHandleView.Mode.LOADING)
        } else {
            error_view.visibility = View.GONE
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun init() {
        isShowValentineDayPromotion = intent.getBooleanExtra("show_valentine_promotion", false)
        isAbleBack = intent.getBooleanExtra("is_able_back", false)
        mAmount = intent.getDoubleExtra("top_amount", 0.0)
        web_view_wing.isVerticalScrollBarEnabled = true
        web_view_wing!!.settings.javaScriptEnabled = true
        web_view_wing!!.webViewClient = mWebViewClient
        mUrlPay = intent.getStringExtra("payment_url").toString()
        Log.d("TAG::>>>", "wingUrl: $mUrlPay")
        web_view_wing!!.loadUrl(mUrlPay)
    }

    private fun onPageFinish(webView: WebView, url: String) {

        when {
            url.contains("result=success") -> {
                exitWingPayment(true)
            }

            url.contains("result=error") -> {
                exitWingPayment(false)
            }
        }
    }

    private fun exitWingPayment(isSuccess: Boolean) {
        showHideLoading(false)

        if (isSuccess) {
            val intent = Intent(this, PaymentActivity::class.java)
            intent.putExtra("show_valentine_promotion", isShowValentineDayPromotion)
            setResult(Activity.RESULT_OK, intent)
        }
        activityExitLeftAnimation()
        finish()

    }

    override fun onBackPressed() {
        closePaymentProcress()
    }

    override fun onPause() {
        super.onPause()
        web_view_wing.onPause()
    }

    override fun onResume() {
        super.onResume()
        web_view_wing.onResume()
    }

    companion object {
        fun lunch(
            context: Context,
            url: String,
            amount: Double,
            isAbleBackPress: Boolean = false,
            ShowValentineDayPromotion: Boolean = false
        ) {
            val i = Intent(context, WingPaymentActivity::class.java)
            i.putExtra("payment_url", url)
            i.putExtra("top_amount", amount)
            i.putExtra("is_able_back", isAbleBackPress)
            i.putExtra("show_valentine_promotion", ShowValentineDayPromotion)
            (context as Activity).startActivityForResult(i, Constant.REQUEST_WING)
        }
    }
}
