package kr.co.icontrols.iotplatform;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.security.MessageDigest;

import kr.co.icontrols.iotplatform.utils.SharedPrefUtil;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ErrorLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.PERMISSIONS;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.PERMISSION_ALL;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.WarnLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.resetBackgroundWaitTime;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_CHECK_VERSION;
import static kr.co.icontrols.iotplatform.utils.SharedPrefUtil.BACKGROUND_WAIT_TIME;
import static kr.co.icontrols.iotplatform.utils.SharedPrefUtil.getBoolean;

public class SplashActivity extends AppCompatActivity {

    private String TAG = SplashActivity.class.getSimpleName();

    private Context mAppContext = null;
    private Handler mHandler = new Handler();
    private static final int SPLASH_DELAY_MILLIS = 1500;
    private String mCurrentVersion;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        mAppContext = getApplicationContext();
        resetBackgroundWaitTime();
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // show the main UI after SPLASH_DELAY_MILLIS
        try {
            mCurrentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
            //TODO - 버전 표시해야함.
            //((TextView)findViewById(R.id.txtVersion)).setText("Ver : " + mCurrentVersion);
        } catch (PackageManager.NameNotFoundException e){
            e.printStackTrace();
            mCurrentVersion= "";
        }

        GetVersionCode getVersionCode = new GetVersionCode();
        getVersionCode.execute();
        //mHandler.postDelayed(mStartMainUIActivityRunnable, SPLASH_DELAY_MILLIS);
        //getAppKeyHash();
    }


    private void getAppKeyHash() {
        try {
            PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md;
                md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                String something = new String(Base64.encode(md.digest(), 0));
                ErrorLogOutput("Hash key", something);
            }
        } catch (Exception e) {
            ErrorLogOutput("name not found", e.toString());
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_CHECK_VERSION:
                if(resultCode == Activity.RESULT_OK) {
                    final String appPackageName = getPackageName();
                    try {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
                    } catch (android.content.ActivityNotFoundException anfe) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
                    }
                } else {
                    mHandler.postDelayed(mStartMainUIActivityRunnable, SPLASH_DELAY_MILLIS);
                }
                break;
        }
    }

    /**
     * 퍼미션 요청이 필요 유무 체크 함수
     * @return
     */
    private boolean needRequestRuntimePermissions() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }

    /**
     * 퍼미션 수락 상태 체크 함수
     * @param context
     * @param permissions 퍼미션 List
     * @return
     */
    public static boolean hasPermissions(Context context, String... permissions) {
        if (context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 스플레시 일정 시간 후 로그인 화면 또는
     */
    private Runnable mStartMainUIActivityRunnable = new Runnable() {
        @Override
        public void run() {
            if(needRequestRuntimePermissions()) {
                if (!hasPermissions(SplashActivity.this, PERMISSIONS)) {
                    ActivityCompat.requestPermissions(SplashActivity.this, PERMISSIONS, PERMISSION_ALL);
                } else {
                    goToLoginActivity();
                }
            } else {
                goToLoginActivity();
            }
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == PERMISSION_ALL){
            boolean isGoToLoginActivity = true;
            for(int i = 0;i<permissions.length;i++){
                if(permissions[i].equals(android.Manifest.permission.CALL_PHONE) && grantResults[i] != PERMISSION_GRANTED){
                    isGoToLoginActivity = false;
                } else if(permissions[i].equals(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[i] != PERMISSION_GRANTED){
                    isGoToLoginActivity = false;
                } else if(permissions[i].equals(Manifest.permission.READ_EXTERNAL_STORAGE) && grantResults[i] != PERMISSION_GRANTED){
                    isGoToLoginActivity = false;
                } else if(permissions[i].equals(android.Manifest.permission.CAMERA) && grantResults[i] != PERMISSION_GRANTED){
                    isGoToLoginActivity = false;
                } else if(permissions[i].equals(android.Manifest.permission.ACCESS_FINE_LOCATION) && grantResults[i] != PERMISSION_GRANTED){
                    isGoToLoginActivity = false;
                }
            }

            if(isGoToLoginActivity){
                goToLoginActivity();
            } else {
                goToPermissionActivity();
            }
        }
    }

    /**
     * 로그인 화면 이동.
     */
    private void goToLoginActivity(){
        Intent intent;
        if(getBoolean(SharedPrefUtil.SHOW_SMART_GUIDE,SharedPrefUtil.DEFAULT_SHOW_SMART_GUIDE)) {
            intent = new Intent(mAppContext, SmartGuideActivity.class);
        } else {
            intent = new Intent(mAppContext, LoginActivity.class);
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }

    /**
     * 권한 요청 화면 이동
     */
    private void goToPermissionActivity(){
        /*
        Intent intent = new Intent(mAppContext, PermissionActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
         */
        Toast.makeText(this, "권한 설정 후 사용이 가능합니다.", Toast.LENGTH_SHORT).show();
        finish();
    }

    /**
     * 앱 업데이트 팝업 표시.
     */
    private void showPopupGoToMarket(){
        Intent intent = new Intent(SplashActivity.this,PopupActivity.class);
        intent.putExtra(PopupActivity.POPUP_MODE,PopupActivity.MODE_YESNO);
        intent.putExtra(PopupActivity.POPUP_BODY_TEXT,getString(R.string.popup_upgrade_app));
        intent.putExtra(PopupActivity.POPUP_OK_BUTTON_TEXT,getString(R.string.upgrage));
        intent.putExtra(PopupActivity.POPUP_CANCEL_BUTTON_TEXT,getString(R.string.late));
        startActivityForResult(intent,RESULT_CHECK_VERSION);
    }

    /**
     * 앱 버전 체크 함수
     */
    public class GetVersionCode extends AsyncTask<Void, String, String> {
        @Override
        protected String doInBackground(Void... voids) {
            String newVersion = null;
            try {
                Document doc = Jsoup
                        .connect("https://play.google.com/store/apps/details?id="+getPackageName())
                        .get();
                Elements Version = doc.select(".htlgb").eq(6);
                for (Element mElement : Version) {
                    newVersion = mElement.text().trim();
                }
                return newVersion;
            } catch (Exception e) {
                return newVersion;
            }
        }

        @Override
        protected void onPostExecute(String onlineVersion) {
            super.onPostExecute(onlineVersion);
            if (!mCurrentVersion.isEmpty() && onlineVersion != null && !onlineVersion.isEmpty()) {
                if (mCurrentVersion.equals(onlineVersion)) {
                    mHandler.postDelayed(mStartMainUIActivityRunnable, SPLASH_DELAY_MILLIS);
                } else {
                    showPopupGoToMarket();
                }
            } else {
                //showPopupGoToMarket();
                mHandler.postDelayed(mStartMainUIActivityRunnable, SPLASH_DELAY_MILLIS);
            }
            WarnLogOutput(TAG, "Current version " + mCurrentVersion + " / playstore version " + onlineVersion);
        }
    }
}