package com.dbs.consent.demo.util;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.format.Formatter;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.dbs.consent.demo.R;
import com.dbs.consent.demo.activity.ConsentActivity;
import com.dbs.consent.demo.activity.LoginActivity;
import com.dbs.consent.demo.consent.sign.SignWrapper;
import com.dbs.consent.demo.customView.CustomAlertDialog;
import com.dbs.consent.demo.customView.NetworkErrorAlert;
import com.dbs.consent.demo.httpTask.CallBack;
import com.dbs.consent.demo.httpTask.HttpRunnable;

import org.kobjects.base64.Base64;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.NetworkInterface;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class Util {
  private static final String TAG = "Util";

  public static String getIpAddress(Context context) {
    WifiManager wm = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
    String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
    return ip;
  }

  public static void networkErrorAlert(final AppCompatActivity mActivity) {
    final CustomAlertDialog csAlert = new CustomAlertDialog(mActivity);
    csAlert.show();
    csAlert.setContent(mActivity.getString(R.string.networkError), ConsentConfig.RETURN_NULL);

    csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        csAlert.dismiss();
        mActivity.finishAffinity();
      }
    });

  }

  public static String getNull2EmptyString(String value) {
    if(value == null || "null".equals(value)) {
      return "";
    }
    return value;
  }

  public static String nullToBlink(String value) {
    if (value == null) {
      value = "";
    }

    return value;
  }

  /**
   * 현재날짜을 가져온다
   * @author jksong
   * @Param
   * @since 2019-06-17 오후 3:49
   **/
  public static int[] toDayDate() {
    Calendar calendar = new GregorianCalendar(Locale.KOREA);
    int nYear = calendar.get(Calendar.YEAR);
    int nMonth = calendar.get(Calendar.MONTH) + 1;
    int nDay = calendar.get(Calendar.DAY_OF_MONTH);

    int toDayDate[] = {nYear, nMonth, nDay};
//    String toDayDate[] = {String.valueOf(nYear), String.valueOf(nMonth), String.valueOf(nDay)};
    return toDayDate;
  }

  /**
   * wifi 연결 여부 체크
   * @author jksong
   * @Param
   * @since 2019-12-05 오전 9:30
   **/
  public static boolean checkWifi(Context context) {
    boolean rtn = false;

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
    NetworkInfo ni         = cm.getActiveNetworkInfo();

    if(ni != null) {
      if(ni.getType() == ConnectivityManager.TYPE_WIFI) {
        rtn = ni.isConnected();
      }
    }

    return rtn;
  }

  /**
   * 데이터 연결 여부 체크
   * @author jksong
   * @Param
   * @since 2019-12-05 오전 9:31
   **/
  public static boolean checkLTE(Context context) {
    boolean rtn = false;

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
    NetworkInfo ni         = cm.getActiveNetworkInfo();

    if(ni != null) {
      if(ni.getType() == ConnectivityManager.TYPE_MOBILE) {
        rtn = ni.isConnected();
      }
    }

    return rtn;
  }

  /**
   * checkWifi, checkLTE 중 하나라도 연결되어 있으면 네트웍이 가능하다고 판단
   * @author jksong
   * @Param
   * @since 2019-12-05 오전 9:31
   **/
  public static boolean checkNetwork(Context context) {
    boolean rtn = false;

    if(checkLTE(context) || checkWifi(context)) {
      rtn = true;
    } else {
      rtn = false;
    }

    return rtn;
  }

  /**
   * WIFI ssid 비교
   * @author jksong
   * @Param Context, wifi ssid
   * @since 2019-06-14 오전 10:50
   **/
  public static boolean checkWifi(Context context, String ssid) {
    WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = manager.getConnectionInfo();
    String wifiSSID = wifiInfo.getSSID().toUpperCase();
    wifiSSID = wifiSSID.substring(1, wifiSSID.length() - 1);

    if (wifiSSID == null) {
      return false;
    }
    return wifiSSID.equals(ssid);
  }

  /**
   * 허용된 WIFI환경인지 체크
   * @author jksong
   * @Param Context
   * @since 2019-06-14 오전 11:02
   **/
//  public static boolean authWifiCheck(Context mContext) {
//    boolean bWifi = false;
//
//    for (String name : ConfigConstants.SSID) {
//      String sName = name.toUpperCase();
//      bWifi = checkWifi(mContext, sName);
//
//      if (bWifi == true) {
//        break;
//      }
//    }
//
//    return bWifi;
//  }

  /**
   * SSID를 "," 구분해서 문자열로 변환
   * @author jksong
   * @since 2019-06-14 오전 11:29
   **/
//  public static String getSsidName() {
//    String wifiNames = String.join(", ", ConfigConstants.SSID);
//    return wifiNames;
//  }

  /**
   * DeviceMacAddress 가져오기
   * @author jksong
   * @Param
   * @since 2019-08-22 오후 8:37
   **/
  public static String getMACAddress() {
    try {
      List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
      for (NetworkInterface intf : interfaces) {
        if (!intf.getName().equalsIgnoreCase("wlan0")) continue;
        byte[] mac = intf.getHardwareAddress();
        if (mac==null) return "";
        StringBuilder buf = new StringBuilder();
        for (int idx=0; idx<mac.length; idx++)
          buf.append(String.format("%02X:", mac[idx]));
        if (buf.length()>0) buf.deleteCharAt(buf.length()-1);
        return buf.toString();
      }
    } catch (Exception ex) { } // for now eat exceptions
    return "";
  }
//  String macAddress = getMACAddress("wlan0");

  public static String nowDate() {
    SimpleDateFormat format = new SimpleDateFormat ( "yyyy/MM/dd");
    Date date = new Date();
    String strDate = format.format(date);
    return strDate;
  }

  public static String logTime() {
    SimpleDateFormat format = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss");
    Date date = new Date();
    String strDate = format.format(date);
    return strDate;
  }

  /**
   * 문자열에 / (슬러쉬)를 제거한다
   * @author jksong
   * @Param
   * @since 2019-08-12 오전 9:00
   **/
  public static String removeSlashStr(String str) {
    str = str.replace("/", "");
    return str;
  }

  /**
   * 날짜 포맷에 / (슬러쉬)를 추가한다
   * @author jksong
   * @Param
   * @since 2019-12-05 오전 9:33
   **/
  public static String addSlashDate(String dateStr) {
    String resDate = "";
    try {
      SimpleDateFormat df = new SimpleDateFormat("yyyymmdd");
      Date date = df.parse(dateStr);
      SimpleDateFormat df1 = new SimpleDateFormat("yyyy/mm/dd");
      resDate = df1.format(date);
    } catch (ParseException e) {
      e.printStackTrace();
    }

    return resDate;
  }

  /**
   * 주민등록번호 앞자리를 생년월일로 변환함
   * @author jksong
   * @Param
   * @since 2019-08-30 오후 2:12
   **/
  public static String changeJuminToBirthday(String dateStr) {

    String resDate = "";
    try {
      SimpleDateFormat df = new SimpleDateFormat("yymmdd");
      Date date = date = df.parse(dateStr);
      SimpleDateFormat df1 = new SimpleDateFormat("yyyy년 mm월 dd일");
      resDate = df1.format(date);
    } catch (ParseException e) {
      e.printStackTrace();
    }

    return resDate;
  }

  public static String changeJuminToBirthday2(String dateStr) {

    String resDate = "";
    try {
      SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
      Date date = date = df.parse(dateStr);
      SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
      resDate = df1.format(date);
    } catch (ParseException e) {
      e.printStackTrace();
    }

    return resDate;
  }

  /**
   * 한자리 숫자 일때 앞에 0을 붙여준다
   * @author jksong
   * @Param integer
   * @since 2019-06-17 오후 3:50
   **/
  public static String plusZero(int num) {
    int temp = num;
    int length = (int) (Math.log10(temp) + 1);
    String d = "";

    if (length == 1) {
      d = String.format("%02d", temp);
    } else {
      d = String.valueOf(temp);
    }

    return d;
  }

  /**
   * 앱 이름을 가져온다
   * @author jksong
   * @Param Context
   * @since 2019-08-08 오후 7:47
   **/
  public static String getAppName(Context mContext) {
    ApplicationInfo applicationInfo = mContext.getApplicationInfo();
    int stringId = applicationInfo.labelRes;
    return stringId == 0 ? applicationInfo.nonLocalizedLabel.toString() : mContext.getString(stringId);
  }

  /**
   * 앱 버전 가져오기
   * @author jksong
   * @Param
   * @since 2019-10-25 오후 5:07
   **/
  public static String getVersion(Context context) {
    String version = null;

    try {
      PackageInfo i = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
      version = i.versionName;
    } catch (PackageManager.NameNotFoundException e) {

    }

    return version;
  }

  /**
   * SharedPreferences String type data 저장
   * @author jksong
   * @Param Context, 저장될 타입, key, value
   * @since 2019-08-08 오후 7:47
   **/
  public static void setStringPreference(Context context, String type, String key, String value) {
    SharedPreferences prefs = context.getSharedPreferences(type, context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(key, value);
    editor.commit();
  }

  /**
   * SharedPreferences String type data 가져오기
   * @author jksong
   * @Param Context, 저장했던 타입, key
   * @since 2019-08-08 오후 7:47
   **/
  public static String getStringPreference(Context context, String type, String key) {
//    SharedPreferences prefs = context.getSharedPreferences(type, context.MODE_MULTI_PROCESS);
    SharedPreferences prefs = context.getSharedPreferences(type, context.MODE_PRIVATE);
    String rtn = prefs.getString(key, "");

    return rtn;
  }

  /**
   * SharedPreferences 저장한 타입을 모두 제거
   * @author jksong
   * @Param Context, 저장한 type
   * @since 2019-08-08 오후 7:47
   **/
  public static void clearPreference(Context context, String type) {
//    SharedPreferences prefs = context.getSharedPreferences(type, context.MODE_MULTI_PROCESS);
    SharedPreferences prefs = context.getSharedPreferences(type, context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.clear();
    editor.commit();
  }

  /**
   * sha256 passwd encrypt
   * @author jksong
   * @Param
   * @since 2019-08-08 오후 7:47
   **/
  public static String sha256Encrypt(String str) {
    String SHA = "";

    try {
      MessageDigest sh = MessageDigest.getInstance("SHA-256");
      sh.update(str.getBytes());
      byte byteData[] = sh.digest();
      StringBuffer sb = new StringBuffer();

      for (int i = 0; i < byteData.length; i++) {
        sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
      }

      SHA = sb.toString();

    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      SHA = null;
    }

    return SHA;
  }

  /**
   * SHA-256 hash
   *
   * @param salt
   * @param data
   * @return
   * @throws Exception
   */
  public static String sha256(String salt, byte[] data) throws Exception {
    if (data == null) {
      throw new Exception("Hash를 적용할 데이터가 없음");
    }

    try {
      final MessageDigest digest = MessageDigest.getInstance("SHA-256");
      // 초기화
      digest.reset();
      if (salt != null) {
        salt = salt.trim();
        if (!"".equals(salt)) {
          digest.update(salt.getBytes());
        }
      }

      // 데이터의 hash값 구하기
      final byte[] hash = digest.digest(data);
      final StringBuilder hexString = new StringBuilder();

      for (final byte element : hash) {
        final String hex = Integer.toHexString(0xff & element);
        if (hex.length() == 1) {
          hexString.append('0');
        }
        hexString.append(hex);
      }

      return hexString.toString();
    } catch (final Exception ex) {
      throw new Exception("SHA-256적용 실패", ex);
    }

  }

  /**
   * MD5 encrypt
   * @author jksong
   * @Param
   * @since 2019-11-19 오후 7:09
   **/
  public static String md5(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    byte[] digest = md5.digest(input.getBytes("UTF-8"));
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < digest.length; ++i) {
      sb.append(Integer.toHexString((digest[i] & 0xFF) | 0x100).substring(1, 3));
    }
    return sb.toString();
  }

  /**
   * 시간 더하기 빼기
   * @author jksong
   * @Param
   * @since 2019-08-30 오후 2:35
   **/
  public static String addDate(String fromDate, String format, int addYear, int addMonth, int addDate, int addHour, int addMinute) {

    SimpleDateFormat sdf = new SimpleDateFormat(format);
    Date date = null;
    try {
      date = sdf.parse(fromDate);

      Calendar cal = new GregorianCalendar();

      cal.setTime(date);
      cal.add(Calendar.YEAR, +addYear);
      cal.add(Calendar.MONTH, +addMonth);
      cal.add(Calendar.DATE, +addDate);
      cal.add(Calendar.HOUR, +addHour);
      cal.add(Calendar.MINUTE, +addMinute);
//    cal.add(Calendar.SECOND, +addSecond);

      SimpleDateFormat sdf2 = new SimpleDateFormat(format);
      String toDate = sdf2.format(cal.getTime());

      return toDate;
    } catch (ParseException e) {
      e.printStackTrace();
    }

    return "";
  }

  private static AlertDialog createDialog(Context context, String title, String msg, String button1, DialogInterface.OnClickListener button1Listener, String button2, DialogInterface.OnClickListener button2Listener) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(context, android.R.style.Theme_Holo_Light_Dialog));

    builder.setTitle(title);
    builder.setMessage(msg);
    builder.setPositiveButton(button1, button1Listener);
    if (button2Listener != null) {
      builder.setNegativeButton(button2, button2Listener);
    }
    builder.setCancelable(false);

    return builder.create();
  }

  public static AlertDialog getOKDialog(Context context, String title, String msg, DialogInterface.OnClickListener okListener) {
    String okId = context.getString(R.string.confirm);
    AlertDialog dlg = createDialog(context, title, msg, okId, okListener, "", null);
    dlg.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

    return dlg;
  }

  public static AlertDialog getPasswordInputDialog(Context context, String title, String msg, DialogInterface.OnClickListener okListener, DialogInterface.OnClickListener cancelListener) {
//    int okId = MPlusResourceUtil.getStringIdByName(context, "mf_ok_button_str");
//    int cancelId = MPlusResourceUtil.getStringIdByName(context, "mf_cancel_button_str");

    String okId = context.getString(R.string.confirm);
    String cancelId = context.getString(R.string.cancel);

    AlertDialog dlg = createDialog(context, title, msg, okId, okListener, cancelId, cancelListener);
    dlg.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    return dlg;
  }

  public static void setCursorColor(EditText view, int color) {
    try {
      // Get the cursor resource id
      Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
      field.setAccessible(true);
      int drawableResId = field.getInt(view);

      // Get the editor
      field = TextView.class.getDeclaredField("mEditor");
      field.setAccessible(true);
      Object editor = field.get(view);

      // Get the drawable and set a color filter
      Drawable drawable = ContextCompat.getDrawable(view.getContext(), drawableResId);
      drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
      Drawable[] drawables = {drawable, drawable};

      // EditTextView underLine color
      Drawable drawable1 = view.getBackground();
      drawable1.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
      view.setBackground(drawable1);

      // Set the drawables
      field = editor.getClass().getDeclaredField("mCursorDrawable");
      field.setAccessible(true);
      field.set(editor, drawables);
    } catch (Exception ignored) {
    }
  }

  public static String convertDateString(Date date, String format) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.getDefault());
    return dateFormat.format(date);
  }

  public static void LOG(Class<?> clazz, String msg) {

    printDebug(clazz, msg, "error");
    //Log.d(MPlusFrameworkConstants.LOG_TAG, buildMessage(clazz, msg));

  }

  private static void printDebug(Class<?> clazz, String msg, String logType) {
    byte[] msgByte = msg.getBytes();
    int startIndex = 0;
    int bufferSize = 3500;
    while(msgByte.length > bufferSize) {
      if (logType.equals("error")) {
        Log.e("JKSONG", buildMessage(clazz, new String(msgByte, startIndex, bufferSize-startIndex)));
      } else {
        Log.d("JKSONG", buildMessage(clazz, new String(msgByte, startIndex, bufferSize-startIndex)));
      }

      startIndex = bufferSize;
      bufferSize = bufferSize + 3500;
    }

    if (logType.equals("error")) {
      Log.e("JKSONG", buildMessage(clazz, new String(msgByte, startIndex, msgByte.length-startIndex)));

    } else {
      Log.d("JKSONG", buildMessage(clazz, new String(msgByte, startIndex, msgByte.length-startIndex)));
    }

  }

  private static final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault());

  /**
   * 메시지 만들기
   * @param clazz 로그를 찍는 클래스
   * @param msg 메시지
   * @return 출력할 형태의 메시지
   */
  private static String buildMessage(Class<?> clazz, String msg) {
    final StringBuilder builder = new StringBuilder();

    // 시간
    builder.append(format.format(new Date())).append(" ");
    // 클래스명
    builder.append("[").append(clazz.getSimpleName()).append("] ");
    if(msg != null) {
      builder.append(msg);
    }

    return builder.toString();
  }

  /**
   * base64Encode
   * @author jksong
   * @Param
   * @since 2019-09-09 오전 8:29
   **/
  public static String base64Encode(String text) throws UnsupportedEncodingException {
    byte[] data = text.getBytes("UTF-8");
    return Base64.encode(data);
    //return Base64.encodeToString(data, Base64.NO_WRAP);     //Android에서 Base64 인코딩 시에 개행문자를 삽입하지 않는 옵션은 NO_WRAP입니다.
  }

  /**
   * base64Encode
   * @author jksong
   * @Param
   * @since 2019-09-09 오전 8:29
   **/
  public static String base64Encode(byte[] digest) throws UnsupportedEncodingException {
    return Base64.encode(digest);
  }

  /**
   * GZip를 이용한 스트링 압축
   * @author jksong
   * @Param
   * @since 2019-09-09 오전 8:30
   **/
  public static byte[] zipStringToBytes(String input) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(gzipOutputStream);
    bufferedOutputStream.write(input.getBytes());
    bufferedOutputStream.close();
    byteArrayOutputStream.close();
    return byteArrayOutputStream.toByteArray();
  }

  /**
   * GZIPInputStream을 이용하여 byte배열 압축해제하기
   * @author jksong
   * @Param
   * @since 2019-09-09 오전 8:30
   **/
  public String unzipStringFromBytes(byte[] bytes) throws IOException {
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
    GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
    BufferedInputStream bufferedInputStream = new BufferedInputStream(gzipInputStream);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    byte[] buffer = new byte[100];
    int length;
    while((length = bufferedInputStream.read(buffer)) > 0) {
      byteArrayOutputStream.write(buffer, 0, length);
    }

    bufferedInputStream.close();
    gzipInputStream.close();
    byteArrayInputStream.close();
    byteArrayOutputStream.close();

    return byteArrayOutputStream.toString();
  }

  /**
  * 루팅방지 코드
  * @author jksong
  * @since 2020-03-05 오전 9:39
  **/
  public static boolean checkSuperUser(Context context) {
    return (checkRootedFiles(context) == true || checkSuperUserCommand(context) == true  || checkSuperUserCommand2(context) == true ||  checkTags(context) == true) ? true : false;
  }

  private static boolean checkRootedFiles(Context context){
    final String[] files = context.getResources().getStringArray(R.array.TEST_PATH);

    for(int i = 0; i<files.length; i++){
      File file = new File(files[i]);
      if(null != file && file.exists()){
        return true;
      }
    }
    return false;
  }

  private static boolean checkTags(Context context) {
    String buildTags = android.os.Build.TAGS;
    if (buildTags != null && buildTags.contains(context.getString(R.string.key))) {
      return true;
    }
    return false;
  }

  private static boolean checkSuperUserCommand(Context context){
    try {
      Runtime.getRuntime().exec(context.getString(R.string.user));
      return true;
    } catch (Error e){
    } catch (Exception e){
    }
    return false;
  }

  private static boolean checkSuperUserCommand2(Context context) {
    Process process = null;
    try {
      process = Runtime.getRuntime().exec(new String[] {context.getString(R.string.tempPath), context.getString(R.string.user)});
      BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
      if (in.readLine() != null) return true;
      return false;
    } catch (Throwable t) {
      return false;
    } finally {
      if (process != null) process.destroy();
    }
  }

  /**
   * api 호출시 세션시간을 검사
   * @author jksong
   * @Param
   * @since 2019-12-05 오전 9:34
   **/
  public static boolean sessionTimeCheck(final Context context) {
    try {
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
      String saveTime = Util.getStringPreference(context, "sessionTime", "sessionTime");
      Date nowDate = new Date();
      String sessionEndTime = dateFormat.format(nowDate);
      int sessionTime = Integer.parseInt(ConsentConfig.SETTING_DATA.get("SESSION_TIME")) == 0 ? 30 : Integer.parseInt(ConsentConfig.SETTING_DATA.get("SESSION_TIME"));
//      int sessionTime = 30;

      String addDateTime = Util.addDate(saveTime, "yyyyMMddHHmm", 0, 0, 0, 0, sessionTime);
      Date saveDateTime = dateFormat.parse(addDateTime);

      Date sessionEndDateTime = dateFormat.parse(sessionEndTime);

      if (saveDateTime.getTime() < sessionEndDateTime.getTime()) {
        final ConsentActivity instance = ((ConsentActivity) context);
        instance.csAlert.show();
        instance.csAlert.setContent(context.getString(R.string.sessionTimeOut), ConsentConfig.ALERT_BTN_TYPE);
        instance.csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            SignWrapper.getInstance().deleteAll();
            Util.clearPreference(context, "userInfo");
            Util.clearPreference(context, "sessionTime");

            instance.csAlert.dismiss();

            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);
            instance.finish();
          }
        });

        return false;
      } else {
        Util.setStringPreference(context, "sessionTime", "sessionTime", sessionEndTime);
        return true;
      }

    } catch (ParseException e) {
      e.printStackTrace();
      return false;
    }

  }

  public static void callHttp(Context context, String soapAction, String callMethod, HashMap<String, String> mData, CallBack callback) {
    if (sessionTimeCheck(context) == true) {
      if (checkNetwork(context) == true) {
        HttpRunnable runnable = new HttpRunnable(soapAction, callMethod, mData, callback);
        Thread thread = new Thread(runnable);
        thread.start();
      } else {
        ((ConsentActivity) context).dismissProgress();
        NetworkErrorAlert networkErrorAlert = new NetworkErrorAlert(context);
        networkErrorAlert.show();
      }
    }
  }
}
