package com.dbs.mplus.knuh.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
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.mplus.knuh.BuildConfig;
import com.dbs.mplus.knuh.R;
import com.dbs.mplus.knuh.consent.sign.SignWrapper;
import com.dbs.mplus.knuh.customView.CustomAlertDialog;
import com.dbs.mplus.knuh.customView.LoadingProgress;
import com.dbs.mplus.knuh.customView.NetworkErrorAlert;
import com.dbs.mplus.knuh.httpTask.CallBack;
import com.dbs.mplus.knuh.httpTask.HttpRunnable;
import com.dbs.mplus.knuh.httpTask.SoapParser;
import com.dbs.mplus.knuh.model.UserLoginDeptList;
import com.dbs.mplus.knuh.util.ConsentConfig;
import com.dbs.mplus.knuh.util.Util;

import org.ksoap2.serialization.SoapObject;

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(true);

//    etId.setText("EMR");
//    etPasswd.setText("wjstkstlf1!");

    // 의사
//    etId.setText("96070");
//    etPasswd.setText("knumc2608?");

//    etId.setText("98130");
//    etPasswd.setText("a56515651!");

//    etId.setText("ENR");
//    etPasswd.setText("wjstkstlf1!");
  }

  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 (Util.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 (Util.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().toUpperCase().trim();
    userPw = etPasswd.getText().toString().trim();
    String certStrFlag = "true";

    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);
        Log.e(TAG, "certFlag -- > " + certFlag);
        if (certFlag == true) {
          Util.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 = Util.sha256Encrypt(userPw);
        Log.e(TAG, "encryptPw -- > " + encryptPw);
      }

      HashMap<String, String> mData = new HashMap<String, String>();
      mData.put("userid", userId);
      mData.put("pwd", 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(SoapObject result) {
        Log.e(TAG, "result -- > " + result);

        if (result == null || result.toString().indexOf("null") > 0) {
          stop();
        } else {
          ArrayList<UserLoginDeptList> arrayList = SoapParser.userLoginDeptList(result);
          if (arrayList.size() == 0) {
            stop();
          } else {
            stop();
            nextActivity(arrayList);
          }
        }


      }

      @Override
      public void stop() {
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            loadingProgress.dismiss();
          }
        });
      };

      @Override
      public void error() {

      }
    };

    if (Util.checkNetwork(mContext) == true) {
      HttpRunnable runnable = new HttpRunnable(ConsentConfig.HOST_HOSPITAL, ConsentConfig.DO_LOGIN, mData, callBack);
      Thread thread = new Thread(runnable);
      thread.start();
    } else {
      loadingProgress.dismiss();
      Util.networkErrorAlert(mActivity);
    }

  }

  private void nextActivity(final ArrayList<UserLoginDeptList> arrayList) {
    runOnUiThread(new Runnable() {
      @Override
      public void run() {

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

          Util.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();

          Util.setStringPreference(mActivity, "userInfo", "deptCd", deptCd);
          Util.setStringPreference(mActivity, "userInfo", "deptNm", deptNm);
          Util.setStringPreference(mActivity, "userInfo", "jobKindCd", jobKindCd);
          Util.setStringPreference(mActivity, "userInfo", "jobKindNm", jobKindNm);
          Util.setStringPreference(mActivity, "userInfo", "userId", userId);
          Util.setStringPreference(mActivity, "userInfo", "userName", userName);
          Util.setStringPreference(mActivity, "userInfo", "indexPage", indexPage);
          Util.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) {
    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();
  }
}
