package com.lemonhc.mplus.mcare_plus.activity

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.view.WindowManager
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.crashlytics.android.Crashlytics
import com.google.android.gms.appindexing.Action
import com.google.android.gms.appindexing.AppIndex
import com.google.android.gms.appindexing.Thing
import com.google.android.gms.common.api.GoogleApiClient
import com.gun0912.tedpermission.PermissionListener
import com.gun0912.tedpermission.TedPermission
import com.lemonhc.mplus.MPlusConstants
import com.lemonhc.mplus.MPlusConstants.APP_NAME
import com.lemonhc.mplus.MPlusConstants.CERT_TYPE
import com.lemonhc.mplus.MPlusConstants.PLATFORM_TYPE
import com.lemonhc.mplus.framework.util.kotlinExtension.chkSIGNATURES
import com.lemonhc.mplus.framework.util.kotlinExtension.cpzmfnxld
import com.lemonhc.mplus.framework.util.kotlinExtension.isCaptureFlag
import com.lemonhc.mplus.framework.util.kotlinExtension.versionCheck
import com.lemonhc.mplus.mcare_plus.R
import io.fabric.sdk.android.Fabric
import java.io.File
import java.util.*


class IntroActivity: AppCompatActivity(){

    private var splash: ImageView? = null
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private var client: GoogleApiClient? = null

    /**
     * 인터텟 가능여부 확인
     * @return
     */
    private val isNetworkConnected:Boolean
        get(){
            val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            return cm.activeNetworkInfo != null
        }

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

        if(isCaptureFlag == false){
            window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
        }

        Fabric.with(this, Crashlytics())
        setContentView(R.layout.activity_intro).run {
//            splash = findViewById(R.id.splash_img) as ImageView
        }

        val helper:SSLTrustHelper = SSLTrustHelper()
        helper.trustEveryone()

        val req_param = mutableListOf<Pair<String, Any?>>().apply {
            add("platformType" to PLATFORM_TYPE)
            add("appName" to APP_NAME)
            add("certType" to CERT_TYPE)
        }


        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = GoogleApiClient.Builder(this).addApi(AppIndex.API).build()
        //오래된 이미지 파일 제거
        this.truncateOrderImageResource()

    }
    
    private fun permissionCheck() {
        val permissionListener: PermissionListener = object : PermissionListener {
            override fun onPermissionGranted() {
                // 버전체크
                checkVersion()
            }
    
            override fun onPermissionDenied(deniedPermissions: ArrayList<String>?) {
                finishAffinity()
            }
        }
        TedPermission.with(applicationContext)
          .setPermissionListener(permissionListener)
          .setRationaleMessage(getString(R.string.permissionCheck))
          .setDeniedMessage(getString(R.string.permissionDenied))
          .setPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE)
          .check()
    }
    
    public override fun onResume() {
        super.onResume()
        checkVersion()
//        permissionCheck()
    }
    
    private fun checkVersion() {
        //버전체크
        if (MPlusConstants.IS_PASS_VERSION_CHECK){
            val handler = Handler()
            handler.postDelayed({
            
                val intent = Intent(this, MainActivity::class.java) // MainActivity.class); //LockScreenActivity
            
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                startActivity(intent)
                finish()
            }, 1000)
        }
        else {
            //버전체크
            this.versionCheck()
        }

//        this.versionCheck()
    
        //무결성검사
        this.chkSIGNATURES()
        //루팅검사
        this.cpzmfnxld()
    }

    public override fun onStart() {
        super.onStart()
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client?.let {
            it.connect()
            AppIndex.AppIndexApi.start(it, getIndexApiAction())
        }
    }

    public override fun onStop() {
        super.onStop()

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client?.let {
            AppIndex.AppIndexApi.end(it, getIndexApiAction())
            it.disconnect()
        }
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    fun getIndexApiAction(): Action {
        val `object` = Thing.Builder()
                .setName("Intro Page")
                // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build()
        return Action.Builder(Action.TYPE_VIEW)
                .setObject(`object`)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build()
    }

    /**
     * 오래된 파일 삭제
     */
    fun truncateOrderImageResource() {
        val photoPath = "${Environment.getExternalStorageDirectory()}/kunkuk"
        val fileOrigins = File(photoPath).listFiles() ?: return

        for (i in 0 until fileOrigins.size) {
            val origin = fileOrigins[i]
            val name = origin.name

            if (name == "thumb") continue
            if (name == ".nomedia") continue

            val currentTime = System.currentTimeMillis()
            val date = java.lang.Long.parseLong(name.subSequence(7, name.length - 4).toString())

            //한달 이상 된 파일의 경우 원본과 썸네일을 삭제한다
            val toMonth = date + 1000 * 60 * 60 * 24 * 30
            if (toMonth > currentTime) {
                val thumb = File("${photoPath}/thumb/${name}")
                thumb.delete()
                origin.delete()
            }
        }
    }


}