package com.hanwha.morakmorak.ui.splash

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.View.*
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.hanwha.morakmorak.databinding.ActivitySplashBinding
import com.hanwha.morakmorak.ui.BindingActivity
import com.hanwha.morakmorak.ui.main.MainActivity
import com.hanwha.morakmorak.util.CommonUtils
import kotlinx.android.synthetic.main.activity_splash.*
import org.koin.android.viewmodel.ext.android.getViewModel
import timber.log.Timber
import java.util.*
import kotlin.concurrent.schedule


class SplashActivity : BindingActivity<ActivitySplashBinding, SplashViewModel>() {

    private lateinit var timerTask: TimerTask

    override fun getLayoutResId() = com.hanwha.morakmorak.R.layout.activity_splash

    override fun getMyViewModel(): SplashViewModel = getViewModel()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding.run {
            lifecycleOwner = this@SplashActivity
            vm = viewModel.apply {
                onSplashClick = {}
                loginComplete = {
                    if (it) {
                        goMain()
                    } else {
                        finish()
                    }
                }
            }
        }
        showSplash()
    }

    /**
     * Full screen 적용
     */
    @SuppressLint("ObsoleteSdkInt")
    override fun configWindow() {
        var uiOption = window.decorView.systemUiVisibility
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
            uiOption = uiOption or SYSTEM_UI_FLAG_HIDE_NAVIGATION
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            uiOption = uiOption or SYSTEM_UI_FLAG_FULLSCREEN
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
            uiOption = uiOption or SYSTEM_UI_FLAG_IMMERSIVE_STICKY

        window.decorView.systemUiVisibility = uiOption
    }

    private fun showSplash() {
        var progress = 0

        timerTask = Timer().schedule(LOADING_MILLIS, LOADING_MILLIS) {
            if (progress == 100) {
//                Timer().schedule(DELAY_MILLIS) {
//                    goMain()
//                }
                runOnUiThread { checkAppPermission() }
            }

            runOnUiThread {
                circularFillableLoaders.setProgress(progress)
                progress += 20
            }
        }
    }

    /**
     * 앱 권한 확인 및 요청
     */
    private fun checkAppPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    arrayOf(Manifest.permission.READ_PHONE_STATE), RECORD_REQUEST_CODE)
        } else {
            Timber.i(CommonUtils.getUuid(this))
            binding.vm!!.login(this)
//            goMain()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int,
                                            permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            RECORD_REQUEST_CODE -> {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 권한을 못 받을 경우
                    finish()
                } else {
                    //권한을 받을 경우
                    binding.vm!!.login(this)
                }
            }
        }
    }

    /**
     * 메인화면 이동
     */
    private fun goMain() {
        timerTask.let {
            it.cancel()
            null
        }
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        finish()
    }

    companion object {
        const val DELAY_MILLIS = 2000L
        const val LOADING_MILLIS = 600L
        // 앱 권한 요청 코드
        const val RECORD_REQUEST_CODE = 1
    }

}
