package com.dbs.dbsec.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telecom.Call;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dbs.dbsec.BuildConfig;
import com.dbs.dbsec.R;
import com.dbs.dbsec.consent.sign.SignWrapper;
import com.dbs.dbsec.customView.CustomAlertDialog;
import com.dbs.dbsec.customView.LoadingProgress;
import com.dbs.dbsec.customView.NetworkErrorAlert;
import com.dbs.dbsec.httpTask.CallBack;
import com.dbs.dbsec.httpTask.HttpCon;
import com.dbs.dbsec.httpTask.HttpRunnable;
import com.dbs.dbsec.httpTask.ParseJsonData;
import com.dbs.dbsec.model.UserLoginDeptList;
import com.dbs.dbsec.util.Common;
import com.dbs.dbsec.util.ConsentConfig;

import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

public class LoginActivity extends AppCompatActivity {

  private static final String TAG = "LoginActivity";
  private AppCompatActivity mActivity;
  private Context mContext;

  private LoadingProgress loadingProgress;
  private CustomAlertDialog csAlert;
  private NetworkErrorAlert ntError;
  private SignWrapper signWrapper;

  private ImageView ivLogo;
  private EditText etId;
  private EditText etPasswd;
  private CheckBox certCheck;
  private Button btnLogin;

  private String userId = "";
  private String userPw = "";

  private long backKeyPressedTime = 0;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    init();
  }

  private void init() {
    mActivity = this;
    mContext  = this;

    loadingProgress = new LoadingProgress(mContext);
    ntError = new NetworkErrorAlert(mContext);
    csAlert = new CustomAlertDialog(mContext);

    setLayout();
    setEvent();
  }

  private void setLayout() {
    ivLogo    = (ImageView) findViewById(R.id.ivLogo);
    etId      = (EditText) findViewById(R.id.etId);
    etPasswd  = (EditText) findViewById(R.id.etPasswd);
    certCheck = (CheckBox) findViewById(R.id.certCheck);
    btnLogin  = (Button) findViewById(R.id.btnLogin);

    int logo = 0;
    if (BuildConfig.INST_CD.equals("032")) {
      logo = R.drawable.chilgok_logo;
    } else {
      logo = R.drawable.knuh_logo;
    }
    ivLogo.setImageResource(logo);
    certCheck.setChecked(false);
    certCheck.setClickable(false);

    etId.setText("EMR");
    etPasswd.setText("dmlfywjdqh3#");
  }

  private void setEvent() {
    btnLogin.setOnClickListener(onClickListener);
    etPasswd.setOnEditorActionListener(onEditorActionListener);
    certCheck.setOnCheckedChangeListener(onCheckedChangeListener);
  }

  private View.OnClickListener onClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      if (btnLogin == v) {
        if (Common.checkNetwork(mContext) == true) {
          loginEvent();
        } else {
          ntError.show();
        }
      }
    }
  };

  private EditText.OnEditorActionListener onEditorActionListener = new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
      if (actionId == EditorInfo.IME_ACTION_DONE) {
        if (v == etPasswd) {
          if (Common.checkNetwork(mContext) == true) {
            loginEvent();
          } else {
            ntError.show();
            loadingProgress.dismiss();
          }
        }
      }
      return false;
    }
  };

  private CheckBox.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
      if (buttonView == certCheck) {
        etPasswd.setText("");
        if (certCheck.isChecked() == true) {
          etPasswd.setHint(getString(R.string.certPwdHint));
        } else {
          etPasswd.setHint(getString(R.string.pwdHint));
        }
      }
    }
  };

  private void loginEvent() {
    loadingProgress.show();
    userId = etId.getText().toString();
    userPw = etPasswd.getText().toString();
    String certStrFlag = "";


    if (userId.equals("")) {
      alertView(getString(R.string.emptyId));
    } else if (userPw.equals("")) {
      String message = "";
      if (certCheck.isChecked() == true) {
        message = getString(R.string.emptyCertPw);
      } else {
        message = getString(R.string.emptyPw);
      }

      alertView(message);
    } else {
      String encryptPw = "";
      // 데모버전에서는 공인인증 기능을 사용할수없음
      if (certCheck.isChecked() == true) {
        certStrFlag = "true";
        signWrapper = SignWrapper.getInstance();
        boolean certFlag = signWrapper.certificate(mContext, userId, userPw);

        if (certFlag == true) {
          Common.setStringPreference(mContext, "userInfo", "certPw", userPw);
        } else {
          btnLogin.setEnabled(true);
          etPasswd.setText("");
          etPasswd.requestFocus();
          loadingProgress.dismiss();
          alertView(getString(R.string.certAuthFail));
          return;
        }
      } else {
        certStrFlag = "false";
        encryptPw = Common.sha256Encrypt(userPw);
      }

      HashMap<String, String> mData = new HashMap<String, String>();
      mData.put("userId", userId);
      mData.put("userPw", encryptPw);
      mData.put("dutInstCd", BuildConfig.INST_CD);
      mData.put("certSucc", certStrFlag);

      loginSubmit(mData);
    }
  }

  private void loginSubmit(HashMap<String, String> mData) {
    CallBack callBack = new CallBack() {
      @Override
      public void result(final String result) {
        Log.e(TAG, "result -- > " + result);
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            loadingProgress.dismiss();
            ArrayList<HashMap<String, String>> rts = Common.parseJSON(mContext, result);
            String code = rts.get(0).get("code");
            if (!code.equals("00")) {
              alertView(getString(R.string.loginFailed));
            } else {
              ArrayList<UserLoginDeptList> deptLists = ParseJsonData.getInstance(mContext).userLoginDeptList(rts);
              if (deptLists.size() == 0) {
                stop();
              } else {
                nextActivity(deptLists);
              }

            }
          }
        });

      }

      @Override
      public void stop() {
        if (certCheck.isChecked() == false) {
          alertView(getString(R.string.loginFailed));
        } else {
          alertView(getString(R.string.certAuthFail));
        }
      }

      @Override
      public void error() {

      }
    };

    if (Common.checkNetwork(mContext ) == true) {
      HttpRunnable runnable = new HttpRunnable(ConsentConfig.DO_LOGIN, mData, callBack);
      Thread thread = new Thread(runnable);
      thread.start();
    } else {
      loadingProgress.dismiss();
      ntError.show();
    }
  }

  private void nextActivity(ArrayList<UserLoginDeptList> arrayList) {
    if (arrayList.size() > 1) {
      Intent intent = new Intent(mContext, DepartmentList.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      intent.putExtra("departmentList", arrayList);
      startActivityForResult(intent, 0);
    } else {
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
      Date nowDate = new Date();
      String nowDateStr = dateFormat.format(nowDate);

      Common.setStringPreference(mContext, "sessionTime", "sessionTime", nowDateStr);

      String deptCd    = arrayList.get(0).getDutplceCd();
      String deptNm    = arrayList.get(0).getDeptHngNm();
      String jobKindCd = arrayList.get(0).getJobKindCd();
      String jobKindNm = arrayList.get(0).getJobKindNm();
      String userId    = arrayList.get(0).getUserId();
      String userName  = arrayList.get(0).getUserName();
      String indexPage = arrayList.get(0).getIndexPage();
      String drKind    = arrayList.get(0).getDrKind();

      Common.setStringPreference(mActivity, "userInfo", "deptCd", deptCd);
      Common.setStringPreference(mActivity, "userInfo", "deptNm", deptNm);
      Common.setStringPreference(mActivity, "userInfo", "jobKindCd", jobKindCd);
      Common.setStringPreference(mActivity, "userInfo", "jobKindNm", jobKindNm);
      Common.setStringPreference(mActivity, "userInfo", "userId", userId);
      Common.setStringPreference(mActivity, "userInfo", "userName", userName);
      Common.setStringPreference(mActivity, "userInfo", "indexPage", indexPage);
      Common.setStringPreference(mActivity, "userInfo", "drKind", drKind);

      Intent intent = new Intent(mActivity, ConsentActivity.class);
      intent.putExtra("deptCd", deptCd);
      intent.putExtra("deptNm", deptNm);
      intent.putExtra("jobKindCd", jobKindCd);
      intent.putExtra("jobKindNm", jobKindNm);
      intent.putExtra("userId", userId);
      intent.putExtra("userName", userName);
      intent.putExtra("indexPage", indexPage);
      intent.putExtra("drKind", drKind);
      startActivity(intent);
      finish();
    }

  }

  private void alertView(String message) {
    csAlert.show();
    csAlert.setContent(message, ConsentConfig.ALERT_BTN_TYPE);
    csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        etPasswd.requestFocus();
        csAlert.dismiss();
      }
    });
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
      finish();
    }
  }

  @Override
  public void onBackPressed() {
    if(System.currentTimeMillis() > backKeyPressedTime + 2000) {
      backKeyPressedTime = System.currentTimeMillis();
      Toast.makeText(mContext, getString(R.string.doublePressed), Toast.LENGTH_SHORT).show();
      return;
    }

    if(System.currentTimeMillis() <= backKeyPressedTime + 2000) {
      finishAffinity();
    }
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
  }
}
