package com.dbs.mplus.consent_demo;

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.Toast;

import com.dbs.consent.demo.activity.LoginActivity;
import com.dbs.consent.demo.customView.CustomAlertDialog;
import com.dbs.consent.demo.httpTask.CallBack;
import com.dbs.consent.demo.httpTask.HttpRunnable;
import com.dbs.consent.demo.httpTask.HttpSoapConnection;
import com.dbs.consent.demo.util.ConsentConfig;
import com.dbs.consent.demo.util.Util;
import com.gun0912.tedpermission.PermissionListener;
import com.gun0912.tedpermission.TedPermission;

import org.ksoap2.serialization.SoapObject;

import java.net.HttpCookie;
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 (Util.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(final SoapObject result) {
        Log.e(TAG, "result --- > " + result);
        Log.e(TAG, "result --- > " + result.getPropertyCount());
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            if (result == null || result.getPropertyCount() == 0) {
//              ConsentConfig.SETTING_DATA.put("SESSION_TIME", "0");
              csAlert.show();
              csAlert.setContent("기본 정보 설정에 실패하였습니다. \n다시 시도해주세요.", ConsentConfig.ALERT_BTN_TYPE);
              csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                  csAlert.dismiss();
                  finishAffinity();
                }
              });
            } else {
              String baseData = result.getProperty("responseData").toString().trim();
              String[] strAr = baseData.split(",");

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

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

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

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

            }
            permissionCheck();
          }
        });

      }

      @Override
      public void stop() {

      }

      @Override
      public void error() {

      }
    };

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

    Log.e(TAG, "mData -- > " + mData);

    if (Util.checkNetwork(mContext) == true) {
      HttpRunnable runnable = new HttpRunnable(ConsentConfig.HOST_HOSPITAL, 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();
  }
}
