package com.swago.login

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInStatusCodes
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.common.api.CommonStatusCodes
import com.permissionx.guolindev.PermissionX
import com.swago.baseswago.activity.BaseXActivity
import com.swago.baseswago.constant.ARouteConstant
import com.swago.baseswago.constant.UrlConstant
import com.swago.baseswago.im.IMMessageManager
import com.swago.baseswago.util.ActivityManagerUtil
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.NoDoubleClickListener
import com.swago.baseswago.util.SwagoLoading
import com.swago.login.databinding.ActivityLoginBinding
import java.util.concurrent.TimeoutException

/**
 *@date 2021/8/24 10:57
 *description:
 */

@Route(path = ARouteConstant.Login.login)
class LoginActivity : BaseXActivity<ActivityLoginBinding>() {

    private val loginVm by viewModels<LoginVm>()
    private var isAccountLogin = false


    override fun loadData() {

    }

    override fun initOther() {
        IMMessageManager.groupMessageParser.clear()
        GoogleLogin.init(this)
        FBLogin.init(object : IFacebook {
            override fun getToken(token: String) {
                loginVm.login("facebook", token)
            }
        })


        binding.clFaceBook.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                if (isInstall(this@LoginActivity,FACEBOOK)){
                    PermissionX.init(this@LoginActivity)
                        .permissions(
                            Manifest.permission.READ_EXTERNAL_STORAGE
                        )
                        .request { allGranted, grantedList, deniedList ->
                            if (allGranted) {
                                FBLogin.login(this@LoginActivity)
                            } else {
                                Toast.makeText(
                                    this@LoginActivity,
                                    "These permissions are denied: $deniedList",
                                    Toast.LENGTH_LONG
                                ).show()
                            }
                        }
                }else{
                    Toast.makeText(AppContext.getContext(), AppContext.getContext().resources.getString(R.string.install_facebook), Toast.LENGTH_SHORT).show()
                }
            }
        })

        binding.clGoogle.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                if (isInstall(this@LoginActivity,GOOGLE)) {
                    PermissionX.init(this@LoginActivity)
                        .permissions(
                            Manifest.permission.READ_EXTERNAL_STORAGE
                        )
                        .request { allGranted, grantedList, deniedList ->
                            if (allGranted) {
                                GoogleLogin.login(this@LoginActivity)
                            } else {
                                Toast.makeText(
                                    this@LoginActivity,
                                    "These permissions are denied: $deniedList",
                                    Toast.LENGTH_LONG
                                ).show()
                            }
                        }
                }else{
                    Toast.makeText(AppContext.getContext(), "", Toast.LENGTH_SHORT).show()
                }
            }
        })

        binding.tvAgreement.setOnClickListener(object: NoDoubleClickListener(){
            override fun onClick() {
                ARouter.getInstance().build(ARouteConstant.Base.webView)
                    .withString("url", UrlConstant.USER_AGREEMENT)
                    .navigation()
            }
        })

        binding.tvPrivacy.setOnClickListener(object: NoDoubleClickListener(){
            override fun onClick() {
                ARouter.getInstance().build(ARouteConstant.Base.webView)
                    .withString("url", UrlConstant.USER_PRIVACY)
                    .navigation()
            }
        })

        binding.tvAccountLogin.setOnClickListener(object: NoDoubleClickListener() {
            override fun onClick() {
                if (isAccountLogin){
                    binding.etAccount.visibility = View.GONE
                    binding.etSecret.visibility = View.GONE
                    binding.tvLogin.visibility = View.GONE
                    binding.clFaceBook.visibility = View.VISIBLE
                    binding.clGoogle.visibility = View.VISIBLE
                    binding.tvAccountLogin.text = AppContext.getContext().resources.getString(R.string.acccount_login)
                }else{
                    binding.etAccount.visibility = View.VISIBLE
                    binding.etSecret.visibility = View.VISIBLE
                    binding.tvLogin.visibility = View.VISIBLE
                    binding.clFaceBook.visibility = View.GONE
                    binding.clGoogle.visibility = View.GONE
                    binding.tvAccountLogin.text = AppContext.getContext().resources.getString(R.string.facebook_google_login)

                }
                isAccountLogin = !isAccountLogin
            }
        })

        binding.tvLogin.setOnClickListener(object:NoDoubleClickListener(){
            override fun onClick() {
                PermissionX.init(this@LoginActivity)
                    .permissions(
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    )
                    .request { allGranted, grantedList, deniedList ->
                        if (allGranted) {
                            SwagoLoading.showLoadingDialog(this@LoginActivity)
                            val account = binding.etAccount.text.toString()
                            val secret = binding.etSecret.text.toString()
                            loginVm.loginByAccount(account, secret)
                        } else {
                            Toast.makeText(
                                this@LoginActivity,
                                "These permissions are denied: $deniedList",
                                Toast.LENGTH_LONG
                            ).show()
                        }
                    }
            }
        })
    }

    override fun initLiveData() {}

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        data?.let { data ->
            if (requestCode == GoogleLogin.requestCode) {
                try {
                    val task = GoogleSignIn.getSignedInAccountFromIntent(data)
                    val result = task.getResult(ApiException::class.java)
                    result?.let {
                        it.idToken?.apply {
                            loginVm.login("google", this)
                        }
                    }
                } catch (e: ApiException) {
                    when (e.statusCode) {
                        GoogleSignInStatusCodes.SIGN_IN_FAILED -> {
                            Toast.makeText(
                                AppContext.getContext(),
                                "login fail-${e.statusCode}",
                                Toast.LENGTH_SHORT
                            ).show()
                        }

                        CommonStatusCodes.CANCELED -> {
                            Toast.makeText(
                                AppContext.getContext(),
                                "login cancel-${e.statusCode}",
                                Toast.LENGTH_SHORT
                            ).show()
                        }

                        else -> {

                        }
                    }
                }
            } else {
                FBLogin.onActivityResult(requestCode, resultCode, data)
            }
        }
    }


    val FACEBOOK = "com.facebook.katana"
    val GOOGLE = "google"
    fun isInstall(activity: Activity, platform:String):Boolean{
        if (platform == GOOGLE){
            val available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(activity)
            return available == 0
        }
        val packageManager = activity.packageManager
        val info = packageManager.getInstalledPackages(0)
        if (info.isEmpty()){
            return false
        }
        info.forEach {
            if (platform == it.packageName){
                return true
            }
        }
        return false
    }
}
