package com.dbs.mplus.fatima.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.dbs.mplus.fatima.R;
import com.dbs.mplus.fatima.customView.CustomAlertDialog;
import com.dbs.mplus.fatima.customView.LoadingProgress;
import com.dbs.mplus.fatima.httpTask.HttpCallBack;
import com.dbs.mplus.fatima.httpTask.HttpConRunnable;
import com.dbs.mplus.fatima.model.UserLoginDeptList;
import com.dbs.mplus.fatima.util.ConsentConfig;
import com.dbs.mplus.fatima.util.Util;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
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 TextView etId;
  private TextView etPasswd;
  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;
    csAlert   = new CustomAlertDialog(mContext);
    loadingProgress = new LoadingProgress(mContext);

    setLayout();
    setEvent();
  }

  private void setLayout() {
    etId     = (TextView) findViewById(R.id.etId);
    etPasswd = (TextView) findViewById(R.id.etPasswd);
    btnLogin = (Button) findViewById(R.id.btnLogin);

    //의사
//    etId.setText("105435");
//    etPasswd.setText("1812312");

    // 산부인과 의사
//    etId.setText("104012");
//    etPasswd.setText("sysedps!@#");

    //간호사 병동
//    etId.setText("103619");
//    etPasswd.setText("2696615");

    //간호사 외래
//    etId.setText("104591");
//    etPasswd.setText("sysedps!@#");

//    etId.setText("105412");
//    etPasswd.setText("sysedps!@#");
  }

  private void setEvent() {
    btnLogin.setOnClickListener(onClickListener);
  }

  private void loginProcess() {
    userId = etId.getText().toString();
    try {
      userPw = Util.md5(etPasswd.getText().toString());
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    if (userId.equals("")) {
      alertView(getString(R.string.emptyId));
    } else if (userPw.equals("")) {
      alertView(getString(R.string.emptyPw));
    } else {
      if (Util.checkNetwork(mContext) == true) {
        loadingProgress.show();
        HashMap<String, String> mData = new HashMap<String, String>();
        mData.put("userid", userId);
        mData.put("pwd", userPw);

        HttpConRunnable runnable = new HttpConRunnable(ConsentConfig.HOST_HOSPITAL, mData, ConsentConfig.DO_LOGIN, callBack);
        Thread thread = new Thread(runnable);
        thread.start();

      } else {
        loadingProgress.dismiss();
        Util.networkErrorAlert(mActivity);
      }
    }
  }

  private void alertView(final String message) {
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        loadingProgress.dismiss();
        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();
          }
        });
      }
    });
  }

  private View.OnClickListener onClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
      if (view == btnLogin) {
        loginProcess();
      }
    }
  };

  private HttpCallBack callBack = new HttpCallBack() {
    @Override
    public void result(final String result) {
      JSONObject object = Util.xmltoJsonObject(result);
      final String res = Util.xmlToJsonString(object);

      runOnUiThread(new Runnable() {
        @Override
        public void run() {
          if (res.equals("")) {
            alertView(getString(R.string.loginFailed));
          } else {
            ArrayList<HashMap<String, String>> arrayList = Util.parseJSON(mContext, res);
            ArrayList<UserLoginDeptList> userLoginDeptLists = new ArrayList<UserLoginDeptList>();
            for (int i = 0; i < arrayList.size(); i++) {
              HashMap<String, String> mm = arrayList.get(i);
              String emplNo        = mm.get("emplno").trim();
              String name          = mm.get("name").trim();
              String unitNm        = mm.get("unitnm").trim();
              String dutplcedeptCd = mm.get("dutplcedeptcd").trim();
              String dutplceDeptNm = mm.get("dutplcedeptnm").trim();
              String jobKindCd     = mm.get("jobkindcd").trim();
              String jobKindNm     = mm.get("jobkindnm").trim();
              String mobile        = mm.get("mobile").trim();

              jobKindCd = Util.plusZero2("4", Integer.parseInt(jobKindCd));
              userLoginDeptLists.add(new UserLoginDeptList(emplNo, name, unitNm, dutplcedeptCd, dutplceDeptNm, jobKindCd, jobKindNm, mobile));
            }

            String emplNo        = userLoginDeptLists.get(0).getEmplNo();
            String name          = userLoginDeptLists.get(0).getName();
            String unitNm        = userLoginDeptLists.get(0).getUnitNm();
            String dutplcedeptCd = userLoginDeptLists.get(0).getDutplcedeptCd();
            String dutplceDeptNm = userLoginDeptLists.get(0).getDutplceDeptNm();
            String jobKindCd     = userLoginDeptLists.get(0).getJobKindCd();
            String jobKindNm     = userLoginDeptLists.get(0).getJobKindNm();
            String mobile        = userLoginDeptLists.get(0).getMobile();

            Util.setStringPreference(mContext, "userInfo", "emplNo" , emplNo);
            Util.setStringPreference(mContext, "userInfo", "name" , name);
            Util.setStringPreference(mContext, "userInfo", "unitNm" , unitNm);
            Util.setStringPreference(mContext, "userInfo", "dutplcedeptCd", dutplcedeptCd);
            Util.setStringPreference(mContext, "userInfo", "dutplceDeptNm" , dutplceDeptNm);
            Util.setStringPreference(mContext, "userInfo", "jobKindCd" , jobKindCd);
            Util.setStringPreference(mContext, "userInfo", "jobKindNm" , jobKindNm);
            Util.setStringPreference(mContext, "userInfo", "mobile" , mobile);

            loadingProgress.dismiss();
            Intent intent = new Intent(mContext, ConsentActivity.class);
            intent.putExtra("emplNo" , emplNo);
            intent.putExtra("name" , name);
            intent.putExtra("unitNm" , unitNm);
            intent.putExtra("dutplcedeptCd", dutplcedeptCd);
            intent.putExtra("dutplceDeptNm", dutplceDeptNm);
            intent.putExtra("jobKindCd" , jobKindCd);
            intent.putExtra("jobKindNm" , jobKindNm);
            intent.putExtra("mobile" , mobile);
            startActivity(intent);
            finish();
          }
        }
      });


    }

    @Override
    public void stop() {

    }

    @Override
    public void error() {

    }
  };

  @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
  public void onDestroy() {
    super.onDestroy();
  }
}
