package com.dbs.dbsec;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.dbs.dbsec.activity.LoginActivity;
import com.dbs.dbsec.customView.CustomAlertDialog;
import com.dbs.dbsec.httpTask.CallBack;
import com.dbs.dbsec.httpTask.HttpCon;
import com.dbs.dbsec.httpTask.HttpRunnable;
import com.dbs.dbsec.util.Common;
import com.dbs.dbsec.util.ConsentConfig;
import com.gun0912.tedpermission.PermissionListener;
import com.gun0912.tedpermission.TedPermission;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

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

  private CustomAlertDialog csAlert;

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

  private void init() {
    mActivity = this;
    mContext  = this;
    csAlert = new CustomAlertDialog(mContext);

    if (Common.checkSuperUser(mContext) == true) {
      csAlert.show();
      csAlert.setContent(getString(R.string.rootingDeviceMsg), ConsentConfig.ALERT_BTN_TYPE);
      csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          csAlert.dismiss();
          finishAffinity();
        }
      });
    } else {
      setSessionTime();
//      permissionCheck();
    }
  }

  private void setSessionTime() {
    CallBack callBack = new CallBack() {
      @Override
      public void result(String result) {
        Log.e(TAG, "result -- > " + result);
        ArrayList<HashMap<String, String>> arrayList = Common.parseJSON(mContext, result);

        for (int i = 0; i < arrayList.size(); i++) {
          HashMap<String, String> mm = arrayList.get(i);
          String code = mm.get("code");
          if (!code.equals("00")) {
            error();
          } else {
            String data = mm.get("data");
            String[] strAr = data.split(",");

            for (int j = 0; j < strAr.length; j++) {
              String[] dataAr = strAr[j].split("[|]");

              String key   = "";
              String value = "";
              for (int k = 0; k < dataAr.length; k++) {

                if (k == 0) {
                  key = dataAr[k];
                } else {
                  value = dataAr[k];
                }

                ConsentConfig.SETTING_DATA.put(key.trim(), value.trim());
              }
            }

            permissionCheck();
          }

        }
      }

      @Override
      public void stop() {

      }

      @Override
      public void error() {
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            csAlert.show();
            csAlert.setContent(getString(R.string.baseDataError), ConsentConfig.ALERT_BTN_TYPE);
            csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                csAlert.dismiss();
                finishAffinity();
              }
            });
          }
        });
      }
    };

    HashMap<String, String> mData = new HashMap<String, String>();
    mData.put("instCd", BuildConfig.INST_CD);

    if (Common.checkNetwork(mContext) == true) {
      HttpRunnable runnable = new HttpRunnable(ConsentConfig.GET_BASE_DATA, mData, callBack);
      Thread thread = new Thread(runnable);
      thread.start();
    } else {
      csAlert.show();
      csAlert.setContent(getString(R.string.networkError), ConsentConfig.ALERT_BTN_TYPE);
      csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          csAlert.dismiss();
          finishAffinity();
        }
      });
    }
  }

  private void permissionCheck() {
    PermissionListener permissionListener = new PermissionListener() {
      @Override
      public void onPermissionGranted() {
        nextActivity();
      }

      @Override
      public void onPermissionDenied(ArrayList<String> deniedPermissions) {
        finishAffinity();
      }
    };
    TedPermission.with(mContext)
        .setPermissionListener(permissionListener)
        .setRationaleMessage(getString(R.string.permissionCheck))
        .setDeniedMessage(getString(R.string.permissionDenied))
        .setPermissions(android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE)
        .check();
  }

  private void nextActivity() {
    new Handler().postDelayed(new Runnable() {
      @Override
      public void run() {
        // 수행할 내용 입력
        Intent intent = new Intent(mContext, LoginActivity.class);
        startActivity(intent);
        finish();
      }
    }, 2000); // 2초 뒤에 수행할 내용에 입력된게 실행됨, 시간은 사용자에 맞게 변경하면됨
  }

  @Override
  public void onBackPressed() {
    // 뒤로가기 막음
  }

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