package com.dbs.mplus.fatima;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;

import com.dbs.mplus.fatima.activity.LoginActivity;
import com.dbs.mplus.fatima.customView.CustomAlertDialog;
import com.dbs.mplus.fatima.httpTask.HttpCallBack;
import com.dbs.mplus.fatima.httpTask.HttpCon;
import com.dbs.mplus.fatima.util.ConsentConfig;
import com.dbs.mplus.fatima.util.Util;
import com.gun0912.tedpermission.PermissionListener;
import com.gun0912.tedpermission.TedPermission;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ExecutionException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

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

//    try {
//      HashMap<String, String> mData = new HashMap<>();
//      mData.put("userid", "105435");
//      mData.put("pwd", Util.md5("1812312"));
//      HttpCon con = new HttpCon("http://172.16.10.192/HospitalSvc.asmx", mData);
////      HttpCon con = new HttpCon("http://172.16.10.192/ConsentSvc.asmx", mData);
//      String result = con.execute().get();
//      Log.e(TAG, "result -- > " + result);
//
//      JSONObject object = new JSONObject(result);
//      JSONObject object1 = new JSONObject(object.get("soap:Envelope").toString());
//      JSONObject object2 = new JSONObject(object1.get("soap:Body").toString());
//
//      String a = Util.xmlToJsonString(object2);
//
//
//      Log.e(TAG, "a - > " + a);
//      ArrayList<HashMap<String, String>> aaa = Util.parseJSON(mContext, a);
//      Log.e(TAG, "aaaaa -- > " + aaa);
//
//      for (int i = 0; i < aaa.size(); i++) {
//        HashMap<String, String> mm = aaa.get(i);
//        Log.e(TAG, "mmm -- > " + mm);
//      }
//
//    } catch (ExecutionException e) {
//      e.printStackTrace();
//    } catch (InterruptedException e) {
//      e.printStackTrace();
//    } catch (NoSuchAlgorithmException e) {
//      e.printStackTrace();
//    } catch (UnsupportedEncodingException e) {
//      e.printStackTrace();
//    } catch (JSONException e) {
//      e.printStackTrace();
//    }

    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 {
      checkWifi();
//      permissionCheck();
    }
  }

  private void checkWifi() {
    boolean bWifi = Util.checkWifi(mContext, ConsentConfig.WIFI_SSID);
    bWifi = true;
    if (bWifi == false) {
      String message = String.format(getString(R.string.wifiMessage), ConsentConfig.WIFI_SSID);
      csAlert.show();
      csAlert.setContent(message, ConsentConfig.ALERT_BTN_TYPE);
      csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          csAlert.dismiss();
          finishAffinity();
        }
      });
      return;
    } else {
      versionCheck();
//      permissionCheck();
    }
  }

  private void versionCheck() {
    HttpCallBack callBack = new HttpCallBack() {
      @Override
      public void result(final String result) {
        Log.e(TAG, "result -- > " + result);
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            if (result.equals("")) {
              csAlert.show();
              csAlert.setContent(getString(R.string.versionFailed), ConsentConfig.ALERT_BTN_TYPE);
              csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                  csAlert.dismiss();
                  finishAffinity();
                }
              });
            } else {
              JSONObject object = Util.xmltoJsonObject(result);
              JSONObject object1 = null;
              JSONObject object2 = null;
              try {
                object1 = new JSONObject(object.get("GetVersionInfoResponse").toString());
                object2 = new JSONObject(object1.get("GetVersionInfoResult").toString());
                ArrayList<HashMap<String, String>> arrayList = Util.parseJSON(mContext, object2.getString("VersionInfoVO"));
                Log.e(TAG, "res - > " + arrayList);
                for (int i = 0; i < arrayList.size(); i++) {
                  HashMap<String, String> mm = arrayList.get(i);
                  String versionOrder = mm.get("versionOrder");
                  final String downLoadUrl = mm.get("downLoadUrl");

                  if (versionOrder.equals(BuildConfig.VERSION_NAME)) {
                    permissionCheck();
                  } else {
                    String message = String.format(getString(R.string.notMatchedVersion), versionOrder, BuildConfig.VERSION_NAME);
                    csAlert.show();
                    csAlert.setContent(message, ConsentConfig.ALERT_BTN_TYPE);
                    csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View view) {
                        csAlert.dismiss();
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(downLoadUrl));
                        startActivity(intent);
                        finishAffinity();
                      }
                    });
                  }
                }
              } catch (JSONException e) {
                e.printStackTrace();
              }
            }
          }
        });


      }

      @Override
      public void stop() {

      }

      @Override
      public void error() {

      }
    };

    HashMap<String, String> mData = new HashMap<>();
    Util.callHttp(mContext, ConsentConfig.HOST_HOSPITAL, ConsentConfig.GET_VERSION_INFO, mData, callBack);
  }

  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();
      }
    }, 1000); // 1초 뒤에 수행할 내용에 입력된게 실행됨, 시간은 사용자에 맞게 변경하면됨
  }

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

}
