package kr.co.compcareworker.Activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
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.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.gun0912.tedpermission.PermissionListener;
import com.gun0912.tedpermission.normal.TedPermission;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import kr.co.compcareworker.Data.ArrayItem_;
import kr.co.compcareworker.Data.Login.UserItem;
import kr.co.compcareworker.MyApplication;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;

public class Intro extends ActivityBasic implements PermissionListener {

    ImageView intro;
    EditText mem_id, mem_pw;
    TextView loginB;
    ProgressBar progress;
    LinearLayout loginFrame;

    String id, pw, token;

    String SaveMarketVersion;
    String SaveAppVersion;
    Handler mhandler = new Handler();

    Runnable runnable = () -> {
        ArrayList<String> permissions = new ArrayList<>(List.of(
                Manifest.permission.CAMERA,
                Manifest.permission.CALL_PHONE,
                Manifest.permission.ACCESS_FINE_LOCATION
        ));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions.add(Manifest.permission.POST_NOTIFICATIONS);
            permissions.add(Manifest.permission.READ_MEDIA_IMAGES);
        }

        TedPermission.create()
                .setPermissionListener((PermissionListener) this)
                .setDeniedMessage(getString(R.string.permission_alert_message))
                .setPermissions(permissions.toArray(new String[0]))
                .check();
    };

    @Override
    protected void onResume() {
        super.onResume();

        handler.postDelayed(runnable, 2000);

        PackageInfo packageInfo = null;
        try {
            packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageInfo == null)
            Log.e("KeyHash", "KeyHash:null");


        for (Signature signature : packageInfo.signatures) {
            try {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            } catch (NoSuchAlgorithmException e) {
                Log.e("KeyHash", "Unable to get MessageDigest. signature=" + signature, e);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        handler.removeCallbacks(runnable);
    }

    @Override
    protected void init() {
        intro = findViewById(R.id.intro);
        mem_id = findViewById(R.id.mem_id);
        mem_pw = findViewById(R.id.mem_pw);
        loginB = findViewById(R.id.loginB);
        progress = findViewById(R.id.progress);
        loginFrame = findViewById(R.id.loginFrame);
    }

    @Override
    protected void init_Listener() {
        loginB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mem_id.getText().toString().equals("")) {
                    Toast.makeText(context, getString(R.string.must_id), Toast.LENGTH_LONG).show();
                    return;
                }
                if (mem_pw.getText().toString().equals("")) {
                    Toast.makeText(context, getString(R.string.must_pw), Toast.LENGTH_LONG).show();
                    return;
                }

                id = mem_id.getText().toString();
                pw = mem_pw.getText().toString();

                Login();
            }
        });
    }

    @Override
    protected void getMessage(Message msg) {

        if (msg.what == 1) {

            String url = msg.getData().getString("url");

            if (url.equals("proc_login_member")) {

                JsonElement element = new JsonParser().parse(msg.obj.toString());
                JsonObject result_item = element.getAsJsonObject();
                userItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<UserItem>>() {
                }.getType());

                if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {

                    //Toast.makeText(Intro.this, userItem.getMessage(), Toast.LENGTH_SHORT).show();
                    Toast.makeText(context, result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();

                    Common.getInstance().setPref(context, "id", id);
                    Common.getInstance().setPref(context, "pw", pw);

                    Intent intent = new Intent(context, MainActivity.class);
                    startActivity(intent);
                    finish();

                } else {
                    Toast.makeText(context, result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                    //Toast.makeText(context, userItem.getMessage(), Toast.LENGTH_SHORT).show();
                    progress.setVisibility(View.GONE);
                    loginFrame.setVisibility(View.VISIBLE);
                }
            } else if (url.equals("proc_get_app_version")) {
                JsonElement element = new JsonParser().parse(msg.obj.toString());
                JsonObject result_item = element.getAsJsonObject();

                if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {

                    String market_version = result_item.get("resultItem").getAsJsonObject().get("message").toString().replace("\"", "");
                    market_version = market_version.substring(4);
                    String app_version = SaveAppVersion.substring(4);

                    if (Integer.parseInt(market_version) > Integer.parseInt(app_version)) {
                        new AlertDialog.Builder(context)
                                .setMessage("업데이트가 필요합니다.\n업데이트를 해 주세요.")
                                .setPositiveButton("업데이트", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        finish();
                                        Uri uri = Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName());
                                        Intent it = new Intent(Intent.ACTION_VIEW, uri);
                                        startActivity(it);
                                    }
                                })
                                .setCancelable(false)
                                .show();
                    } else {
                        intro.setVisibility(View.GONE);
                        CheckLogin();
                    }
                } else {
                    Common.getInstance().toastShow(context, "앱 버전 체크에 실패했습니다. 잠시 후 다시 시도해주세요.");
                    finish();
                }
            }
        } else if (msg.what == -1) {

            Toast.makeText(context, msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_intro, "인트로");
        MyApplication.myActivity = this;
        super.onCreate(savedInstanceState);
        Log.e("인트로", "인트로 시작");
    }

    @Override
    public void onPermissionGranted() {
        runnable = null;
        Log.e("권한 체크", "권한 체크");
        try {
            checkUpdate();
        } catch (Exception e) {
            intro.setVisibility(View.GONE);
            CheckLogin();
        }
    }

    @Override
    public void onPermissionDenied(List<String> deniedPermissions) {
        for (int i = 0; i < deniedPermissions.size(); i++) {
            Log.d("onPermissionDenied", deniedPermissions.get(i));
        }

        Toast.makeText(Intro.this, getString(R.string.permission_denied_message), Toast.LENGTH_SHORT).show();
        finish();
    }

    void CheckLogin() {

        FirebaseMessaging.getInstance().getToken().addOnSuccessListener(this, new OnSuccessListener<String>() {
            @Override
            public void onSuccess(String s) {
                Log.i("FCM Token", s);
                Common.getInstance().setPref(context, "token", s);
                token = s;

                if (Common.getInstance().getPref(context, "id", false)) {
                    id = Common.getInstance().getPref(context, "id");
                    pw = Common.getInstance().getPref(context, "pw");

                    Login();
                } else {
                    progress.setVisibility(View.GONE);
                    intro.setVisibility(View.GONE);
                    loginFrame.setVisibility(View.VISIBLE);
                }
            }
        }).addOnFailureListener(this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(context, getString(R.string.not_use_app), Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    void Login() {

        progress.setVisibility(View.VISIBLE);

        HashMap<String, String> data = new HashMap<>();
        data.put("mb_type", "ENGINEER");
        data.put("mb_id", id);
        data.put("mb_password", pw);
        data.put("mb_fcm_key", token);
        new ApiClient(data, "proc_login_member", handler);
    }

    void Get_version() {
        HashMap<String, String> data = new HashMap<>();
        data.put("app_name", "WORKER");
        new ApiClient(data, "proc_get_app_version", handler);
    }

    void checkUpdate() {

        try {
//            SaveMarketVersion = new getMarketVersion().execute().get();
            SaveAppVersion = getAppVersion();

        } catch (Exception e) {
            intro.setVisibility(View.GONE);
            CheckLogin();
            e.printStackTrace();
        }

        Get_version();

//        if (!SaveMarketVersion.equals(SaveAppVersion)) {
//            new AlertDialog.Builder(context)
//                    .setMessage("업데이트가 필요합니다.\n업데이트를 해 주세요.")
//                    .setPositiveButton("업데이트", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialogInterface, int i) {
//                            finish();
//                            Uri uri = Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName());
//                            Intent it = new Intent(Intent.ACTION_VIEW, uri);
//                            startActivity(it);
//                        }
//                    })
//                    .setCancelable(false)
//                    .show();
//        } else {
//            intro.setVisibility(View.GONE);
//            CheckLogin();
//        }
    }
//
//    private class getMarketVersion extends AsyncTask<String, String, String> {
//
//        String MarketVersion;
//
//        @Override
//        protected void onPreExecute() {
//            super.onPreExecute();
//        }
//
//        @Override
//        protected String doInBackground(String... params) {
//            try {
//
//                Document doc = Jsoup.connect("https://play.google.com/store/apps/details?id=" + getPackageName()).get();
//                Elements Version = doc.select(".htlgb");
//
//                for (int i = 0; i < Version.size(); i++) {
//                    MarketVersion = Version.get(i).text();
//                    if (Pattern.matches("^[0-9].[0-9].[0-19]$", MarketVersion)) {
//                        break;
//                    }
//                }
//
//                return MarketVersion;
//            } catch (Exception e) {
//                e.printStackTrace();
//                return null;
//            }
//        }
//    }

    private String getAppVersion() {
        PackageManager pm = getPackageManager();
        PackageInfo pInfo = null;

        try {
            pInfo = pm.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e1) {
            e1.printStackTrace();
        }

        String currentVersion = pInfo.versionName;

        return currentVersion;
    }
}
