package kr.co.compcarecompany.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.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
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.OnCompleteListener;
import com.google.android.gms.tasks.Task;
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.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.gun0912.tedpermission.PermissionListener;
import com.gun0912.tedpermission.normal.TedPermission;

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

import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.ArrayItem_;
import kr.co.compcarecompany.Data.Company.CompanyData;
import kr.co.compcarecompany.Data.Company.Partner;
import kr.co.compcarecompany.Data.Memo.Login.UserItem;
import kr.co.compcarecompany.Fragment.FragmentIntentIntegrator;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;

public class Intro extends ActivityBasic implements PermissionListener {

    ImageView introIV;
    EditText mem_idET, mem_pwET;
    TextView loginTV, joinTV, find_pwTV;
    ProgressBar introPB;
    LinearLayout loginFrameLL;
    String id, pw, token, encode_pw;
    ArrayItem_<Partner> partnerItems;
    Partner partnerData;
    String ag_idx, pt_idx, report_type = "";
    String SaveMarketVersion;
    String SaveAppVersion;
    TextView versionTV;
    ArrayItem<CompanyData> companyItems;

    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();
        Intent intent = getIntent();
        if (intent.getStringExtra("report_publish") != null) {
            report_type = intent.getStringExtra("report_publish");
            handler.postDelayed(runnable, 0);
            introIV.setVisibility(View.GONE);
        } else {
            handler.postDelayed(runnable, 2000);
        }
    }

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

    @Override
    protected void init() {
        introIV = findViewById(R.id.introIV);
        mem_idET = findViewById(R.id.mem_idET);
        mem_pwET = findViewById(R.id.mem_pwET);
        loginTV = findViewById(R.id.loginTV);
        joinTV = findViewById(R.id.joinTV);
        find_pwTV = findViewById(R.id.find_pwTV);
        introPB = findViewById(R.id.introPB);
        loginFrameLL = findViewById(R.id.loginFrameLL);
        versionTV = findViewById(R.id.versionTV);
    }

    @Override
    protected void init_Listener() {

        //로그인버튼
        loginTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mem_idET.getText().toString().equals("")) {
                    Toast.makeText(context, getString(R.string.must_id), Toast.LENGTH_LONG).show();
                    return;
                }
                if (mem_pwET.getText().toString().equals("")) {
                    Toast.makeText(context, getString(R.string.must_pw), Toast.LENGTH_LONG).show();
                    return;
                }

                id = mem_idET.getText().toString();
                pw = mem_pwET.getText().toString();

                Login();
            }
        });

        //회원가입
        joinTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                IntentIntegrator integrator = new IntentIntegrator(Intro.this);
                integrator.setCaptureActivity(QRCodeActivity.class);
                integrator.setBarcodeImageEnabled(true);
                integrator.setOrientationLocked(false);
                integrator.initiateScan();

            }
        });

        find_pwTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mem_idET.getText().clear();
                mem_pwET.getText().clear();

//                Intent intent = new Intent(context, FragmentActivity.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
//                intent.putExtra("title", "비밀번호 찾기");
//                intent.putExtra("type", "find_password");
//                startActivity(intent);

//                new Thread(new Runnable() {
//                    public void run() {
//                        // TODO Auto-generated method stub
//                        GMailSender sender = new GMailSender("yjbyun8@gmail.com", "dbswjd11!!");
//                        String msg = sender.sendMail("임시 비밀번호 발송", "요청하신 아이디의 임시 비밀번호는 "+sender.getEmailCode()+" 입니다.\n로그인 후 비밀번호를 반드시 변경해주세요.", "holic0130@naver.com");
//                        postToastMessage(msg);
//                    }
//                }).start();

                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
                dialogBuilder.setTitle("콤프케어 작업자");
                dialogBuilder.setMessage("비밀번호 찾기는 고객센터에 문의바랍니다.\n전화연결 하시겠습니까?");
                dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        try {
                            Uri uri = Uri.parse("tel:" + "01029295541");
                            context.startActivity(new Intent("android.intent.action.DIAL", uri));
                            dialog.dismiss();
                        } catch (Exception e) {
                            Toast.makeText(context, "전화번호 형식이 올바르지 않습니다.", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).setNegativeButton("취소", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.dismiss();
                    }
                });
                dialogBuilder.show();

            }
        });
    }

    @Override
    protected void getMessage(Message msg) {
        String url = msg.getData().getString("url");

        if (msg.what == 1) {

            if (url.equals("proc_login_member3")) {
                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 (userItem.isSuccess()) {
                    Common.getInstance().setPref(context, "id", id);
                    Common.getInstance().setPref(context, "pw", pw);
                    //동시 로그인 제한
                    Common.getInstance().setPref(context, "session_id", userItem.getMessage());

                    HashMap<String, String> data = new HashMap<>();
                    data.put("ag_idx", userItem.getArrayitem().getAgIdx());
                    data.put("pt_idx", userItem.getArrayitem().getPtIdx());
                    data.put("session_id", userItem.getMessage());
                    data.put("mb_id", userItem.getArrayitem().getMbId());
                    data.put("type", "COMPANY");
                    new ApiClient(data, "proc_admin_partner_view2", handler);

                } else {

                    Toast.makeText(context, userItem.getMessage(), Toast.LENGTH_SHORT).show();
                    introPB.setVisibility(View.GONE);
                    loginFrameLL.setVisibility(View.VISIBLE);
                }

            } else if (url.equals("proc_find_member_with_qr")) {
                JsonElement element = new JsonParser().parse(msg.obj.toString());
                JsonObject result_item = element.getAsJsonObject();
                partnerItems = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<Partner>>() {
                }.getType());

                if (partnerItems.isSuccess()) {
                    partnerData = partnerItems.getArrayitem();

                    ag_idx = partnerData.getAgIdx();
                    pt_idx = partnerData.getPtIdx();

                    Bundle bundle = new Bundle();
                    bundle.putString("ag_idx", partnerData.getAgIdx());
                    bundle.putString("pt_idx", partnerData.getPtIdx());
                    bundle.putString("pt_name", partnerData.getPtName());
                    bundle.putString("pt_ceo", partnerData.getPtCeo());
                    bundle.putString("pt_code", partnerData.getPtCode());
                    bundle.putString("pt_tel", partnerData.getPtTel());
                    bundle.putString("pt_condition", partnerData.getPtCondition());
                    bundle.putString("pt_addr", partnerData.getPtAddr());
                    bundle.putString("pt_addr_sub", partnerData.getPtAddrSub());

                    Intent intent = new Intent(context, FragmentActivity.class);
                    intent.putExtra("title", "회원가입");
                    intent.putExtra("type", "join_step_first");
                    intent.putExtra("value1", bundle);
                    startActivity(intent);

                } else {

                    if (partnerItems.getMessage().equals("000")) {
                        Toast.makeText(context, "가입 가능한 잔여 회원수가 없습니다.\n업체에 문의하여 회원수를 조정해주세요.", Toast.LENGTH_SHORT).show();

                    } else if (partnerItems.getMessage().equals("999")) {
                        Toast.makeText(context, "일치하는 QR코드 정보가 없습니다.", Toast.LENGTH_SHORT).show();
                    }
                }

            } else if (url.equals("proc_admin_partner_view2")) {

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

                if (companyItems.isSuccess()) {

                    Intent intent = new Intent(context, MainActivity.class);
                    intent.putExtra("companyData", companyItems.get(0));
                    intent.putExtra("report_type", report_type);
                    startActivity(intent);
                    finish();

                } else {
                    Toast.makeText(context, msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                }
            } 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 {
                        introIV.setVisibility(View.GONE);
                        CheckLogin();
                    }
                } else {
                    Common.getInstance().toastShow(context, "앱 버전 체크에 실패했습니다. 잠시 후 다시 시도해주세요.");
                    finish();
                }
            } else if (url.equals("proc_login_member4")) {

                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 (userItem.isSuccess()) {
                    Common.getInstance().setPref(context, "id", id);
                    Common.getInstance().setPref(context, "pw", pw);
                    //동시 로그인 제한
                    Common.getInstance().setPref(context, "session_id", userItem.getMessage());

                    HashMap<String, String> data = new HashMap<>();
                    data.put("ag_idx", userItem.getArrayitem().getAgIdx());
                    data.put("pt_idx", userItem.getArrayitem().getPtIdx());
                    data.put("session_id", userItem.getMessage());
                    data.put("mb_id", userItem.getArrayitem().getMbId());
                    data.put("type", "COMPANY");
                    new ApiClient(data, "proc_admin_partner_view2", handler);

                } else {

                    Toast.makeText(context, userItem.getMessage(), Toast.LENGTH_SHORT).show();
                    introPB.setVisibility(View.GONE);
                    loginFrameLL.setVisibility(View.VISIBLE);
                }

            }
        } else if (msg.what == 2) {
            Common.getInstance().toastShow(context, "다른 기기에서 접속하여 연결이 끊겼습니다.\n이용을 원하시면 재접속 해주세요.");

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

            Intent i = this.getBaseContext().getPackageManager().
                    getLaunchIntentForPackage(this.getBaseContext().getPackageName());
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);

        } 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, "인트로");
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onPermissionGranted() {
        try {
            checkUpdate();
        } catch (Exception e) {
            introIV.setVisibility(View.GONE);
            CheckLogin();
        }
        runnable = null;
    }

    @Override
    public void onPermissionDenied(List<String> deniedPermissions) {
        Toast.makeText(Intro.this, getString(R.string.permission_denied_message), Toast.LENGTH_SHORT).show();
        finish();
    }

    void CheckLogin() {

        FirebaseMessaging.getInstance().getToken().addOnCompleteListener(this, new OnCompleteListener<String>() {
            @Override
            public void onComplete(@NonNull Task<String> task) {
                if (!task.isSuccessful()) {
                    Toast.makeText(context, getString(R.string.not_use_app), Toast.LENGTH_SHORT).show();
                    finish();

                } else {
                    token = task.getResult();
                    Common.getInstance().setPref(context, "token", token);

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

                    } else {
                        introPB.setVisibility(View.GONE);
                        loginFrameLL.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
    }

    void Login() {
        introPB.setVisibility(View.VISIBLE);
        String[] encrypt_pw = new String[0];

        try {
            encrypt_pw = Common.getInstance().encrypt(pw);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        encode_pw = encrypt_pw[0];

        HashMap<String, String> data = new HashMap<>();
        data.put("mb_type", "COMPANY");
        data.put("mb_id", id);
        data.put("mb_password", pw);
        data.put("mb_fcm_key", token);
        data.put("mb_encode", encode_pw);
        data.put("mb_salt", encrypt_pw[1]);

        new ApiClient(data, "proc_login_member4", handler);

    }

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

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        IntentResult result = FragmentIntentIntegrator.parseActivityResult(requestCode, resultCode, data);

        if (result.getContents() != null && !result.getContents().equals("")) {

            HashMap<String, String> get_data = new HashMap<>();
            get_data.put("qr", result.getContents());
            new ApiClient(get_data, "proc_find_member_with_qr", handler);
        }
    }

    void checkUpdate() {

        try {
            SaveAppVersion = getAppVersion();
            versionTV.setText("Ver " + SaveAppVersion);

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

        Get_version();

    }

    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;
    }
}
