package org.linphone.utils;

import static android.content.Context.INPUT_METHOD_SERVICE;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Handler;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONObject;
import org.linphone.R;
import org.linphone.rest.RestBase;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cz.msebera.android.httpclient.Header;

public class AppMethods {

    private static final String TAG = "AppMethods";
    public static InputFilter space_filter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

            boolean includesInvalidCharacter = false;
            StringBuilder stringBuilder = new StringBuilder();

            int destLength = dend - dstart + 1;
            int adjustStart = source.length() - destLength;
            for (int i = start; i < end; i++) {
                char sourceChar = source.charAt(i);
                if (!Character.isSpaceChar(sourceChar)) {
                    if (i >= adjustStart) stringBuilder.append(sourceChar);
                } else includesInvalidCharacter = true;
            }
            return includesInvalidCharacter ? stringBuilder : null;
        }
    };


    public static void alertWithOk(final Context context, final String message) {

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

        alertDialogBuilder.setMessage(message)
                .setCancelable(false)
                .setPositiveButton(context.getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.cancel();
                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();

        alertDialog.show();

        alertDialog.getWindow().getAttributes();

        TextView textView = (TextView) alertDialog.findViewById(android.R.id.message);
        textView.setTextSize(16);

        Button btn1 = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        btn1.setTextSize(16);
        btn1.setTextColor(context.getResources().getColor(R.color.blue, null));
        btn1.setInputType(0);

    }

    public static boolean isValidEmail(String email) {
        String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    public static boolean isConnectingToInternet(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
        }
        return false;
    }

    public static void alertForNoInternet(final Context context) {
        AlertDialog.Builder alertDialogBuilder;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            alertDialogBuilder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Light_Dialog_Alert);
        } else {
            alertDialogBuilder = new AlertDialog.Builder(context);
        }

        alertDialogBuilder.
                setMessage(context.getResources().getString(R.string.no_internet_connection)).setCancelable(false).setPositiveButton(context.getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

        alertDialog.getWindow().getAttributes();

        TextView textView = (TextView) alertDialog.findViewById(android.R.id.message);
        textView.setTextSize(16);

        Button btn1 = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        btn1.setTextSize(16);
        btn1.setTextColor(context.getResources().getColor(R.color.blue, null));
        btn1.setInputType(0);
    }

    public static void alertWithOk2(Context con, String message) {

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(con);

        alertDialogBuilder.setMessage(message)
                .setCancelable(false)
                .setPositiveButton(con.getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.cancel();
                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();

        alertDialog.show();

        alertDialog.getWindow().getAttributes();

        TextView textView = (TextView) alertDialog.findViewById(android.R.id.message);
        textView.setTextSize(16);

        Button btn1 = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        btn1.setTextSize(16);
        btn1.setTextColor(con.getResources().getColor(R.color.blue, null));
        btn1.setInputType(0);

    }


    /*public static boolean isCodecNeedToBeEnabled(Context context, String codec) {
        if (codec.equals(context.getString(R.string.AudioCodecG729))) {
            return false;
        } else if (codec.equals(context.getString(R.string.AudioCodecPCMA))) {
            return true;
        } else if (codec.equals(context.getString(R.string.AudioCodecPCMU))) {
            return false;
        } else if (codec.equals(context.getString(R.string.AudioCodecGSM))) {
            return false;
        } else if (codec.equals(context.getString(R.string.AudioCodecILBC))) {
            return false;
        } else if (codec.equals(context.getString(R.string.AudioCodecOPUS))) {
            return true;
        } else if (codec.equals(context.getString(R.string.AudioCodecSILK))) {
            return false;
        } else if (codec.equals(context.getString(R.string.AudioCodecSPEEX))) {
            return false;
        } else if (codec.equals(context.getString(R.string.AudioCodecG722))) {
            return true;
        } else {
            return false;
        }
    }*/


    public static boolean isValidPassword(final String password) {

        if (!password.matches(".*[!@#$;,._(){}\\[\\]%^&*+=?-].*")) {


            return false;
        }
        return true;


    }

    public static boolean isValidName(String name) {

        String specialCharacters = "!#$%&'()*+,-./;=?@[]^_{|}";

//         .-_$*()#@!%;{}[]+=?,
        String str2[] = name.split("");
        int count = 0;
        for (int i = 0; i < str2.length; i++) {
            if (specialCharacters.contains(str2[i])) {
                count++;
            }
        }

        if (name != null && count == 0) {
            Log.e(TAG, "isValidName: true ");
            return true;
        } else {
            Log.e(TAG, "isValidName: else");
            return false;
        }
    }

    public static boolean checkingpasswordUpperCase(final String password) {

//        Pattern pattern;
//        Matcher matcher;
//        final String PASSWORD_PATTERN = "(?=.*[A-Z])";
//        pattern = Pattern.compile(PASSWORD_PATTERN);
//        matcher = pattern.matcher(password);
//        Log.e(TAG, "checkingpasswordUpperCase: "+matcher.matches() );
//        return matcher.matches();
        if (!password.matches(".*[A-Z].*")) return false;
        return true;

    }

    public static boolean checkingpasswordLowerCase(final String password) {

//        Pattern pattern;
//        Matcher matcher;
//        final String PASSWORD_PATTERN = "(?=.*[a-z])";
//        pattern = Pattern.compile(PASSWORD_PATTERN);
//        matcher = pattern.matcher(password);
//        Log.e(TAG, "checkingpasswordLowerCase: "+matcher.matches() );
//        return matcher.matches();


        if (!password.matches(".*[a-z].*")) return false;
        return true;

    }

    public static boolean checkingpasswordDigit(final String password) {


        if (!password.matches(".*\\d.*")) return false;

        return true;


    }

    public static boolean checkingSpecialCharacter(final String password) {


        Pattern regex = Pattern.compile("[$&+,:;=?@#|]");
        Matcher matcher = regex.matcher(password);
        Matcher matcher1 = regex.matcher("qwweew@dd");


        return matcher.find();
    }


    public static boolean clean(String str) {

        String regex = "a-zA-Z0-9!@#-=?()$%^&*_;\\[\\].,/}{+";
        if (str.matches("[" + regex + "]+")) {
            System.out.println("matches");
        } else {
            return false;
        }

        return true;
    }

    public static void showToast(Context context, String message) {

        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }

    /*hiding keyboard*/
    public static void hideSoftKeyboard(Activity context) {

        try {
            InputMethodManager inputManager = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            context.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static boolean isAppIsInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }


    public static boolean isCurrentActivityIsLastActivityRunning(Activity activity) {

        boolean isLastActivity = false;
        try {

            ActivityManager mngr = (ActivityManager) activity.getSystemService(activity.ACTIVITY_SERVICE);

            List<ActivityManager.RunningTaskInfo> taskList = mngr.getRunningTasks(10);

            for (int i = 0; i < taskList.size(); i++) {
                Log.i(TAG, "stack : i : " + i + "act name : " + taskList.get(i).topActivity.getClassName().equals(activity.getClass().getName()));
            }


            if (taskList.get(0).numActivities == 1) {
                Log.i(TAG, "This is last activity in the stack");
                isLastActivity = true;
            }

            return isLastActivity;
        } catch (SecurityException e) {
            e.printStackTrace();
        }

        return isLastActivity;
    }

    public static void closeKeyboardAlert(Activity activity) {
        final Dialog dialog = new Dialog(activity);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialog.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                dialog.cancel();
            }
        }, 500);
    }

    public static boolean checkingLocationPermissions(Activity activity) {
        int PERMISSION_ALL = 1;
        String[] PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION};

        if (!hasPermissions(activity, PERMISSIONS)) {
            ActivityCompat.requestPermissions(activity, PERMISSIONS, PERMISSION_ALL);
            return false;
        }
        return true;
    }

    public static boolean hasPermissions(Context context, String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    /*gps connection checking*/
    public static boolean checkGpsOnOff(Context activity) {
        LocationManager locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            return true;
        } else {
            return false;
        }

    }

    public static void alertGps(final Activity activity) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);

        alertDialogBuilder.setMessage(activity.getString(R.string.alert_enable_gps)).setCancelable(false).setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
                activity.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));

            }
        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }

        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    public static void startLocationService(Activity activity) {

/*
            Intent in = new Intent(activity, PlayLocation.class);
            activity.startService(in);*/
    }

    private static void stopLocationService(Activity activity) {


        /*Intent in = new Intent(activity, PlayLocation.class);
        activity.stopService(in);*/


    }

    public static void ShowGpsAlert(final Activity ac, String header, String content) {

        final SessionManager session = new SessionManager(ac);

        final Dialog dialog = new Dialog(ac);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialog.setContentView(R.layout.show_gps);

        TextView rec_del_ok_tv = (TextView) dialog.findViewById(R.id.logout_okay_tv);

        View view = (View) dialog.findViewById(R.id.view);
        view.setVisibility(View.GONE);

        TextView rec_del_cancle_tv = (TextView) dialog.findViewById(R.id.logout_no_tv);

        TextView header_title_tv = (TextView) dialog.findViewById(R.id.header_title_tv);

        rec_del_ok_tv.setText(ac.getResources().getString(R.string.cancel));

        rec_del_cancle_tv.setText(ac.getResources().getString(R.string.settings));
        header_title_tv.setText(header);
        rec_del_cancle_tv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                ac.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));

                AppMethods.startLocationService(ac);
                dialog.cancel();

            }
        });
        rec_del_ok_tv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                dialog.cancel();

            }
        });
        dialog.show();

    }

   /* public static  void updateLocationApiCall(Context context) {

        SessionManager sessionManager = new SessionManager(context);

        if (AppMethods.isConnectingToInternet(context)) {
            JSONObject jo = null;
            try {
                jo = new JSONObject();
                jo.put(AppStrings.InputParams.action, RestApis.action_update);
                jo.put(AppStrings.InputParams.login, sessionManager.getStoreData(AppStrings.Session.login));
                jo.put(AppStrings.InputParams.password, sessionManager.getStoreData(AppStrings.Session.password));

                JSONObject job = new JSONObject();
                job.put(AppStrings.UpdateLocation.latitude, String.valueOf(PlayLocation.playlat));
                job.put(AppStrings.UpdateLocation.longitude, String.valueOf(PlayLocation.playlog));

                jo.put(AppStrings.InputParams.params, job);

                try {
                    FileOperations.writeLocationUpdate(
                            AppStrings.InputParams.action+ ":" + RestApis.action_update + "\n"
                            + AppStrings.UpdateLocation.latitude+":" + String.valueOf(PlayLocation.playlat)+ "\n"
                            + AppStrings.UpdateLocation.longitude+":" + String.valueOf(PlayLocation.playlog) + "\n"
                            + " job:" + job.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            postJsonAsyncHttp(context,RestApis.url, RestApis.action_update, jo);

        }
    }*/


    public static void postJsonAsyncHttp(final Context context, final String URL, final String api_name, final JSONObject postParams) {
        final long firstime = System.currentTimeMillis();
        RestBase.postJson(context, URL, postParams, new JsonHttpResponseHandler() {


            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                float ftime = (System.currentTimeMillis() - firstime) / 1000;

                try {
                    uodateLocationResponse(context, response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                super.onSuccess(statusCode, headers, responseString);


            }


            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                try {

                    if (statusCode == AppIntegers.Unauthorized) {

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                try {

                    if (statusCode == AppIntegers.Unauthorized) {

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                try {

                    if (statusCode == AppIntegers.Unauthorized) {

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        });
    }

    public static void uodateLocationResponse(Context context, String response) {
        try {
            SessionManager sessionManager = new SessionManager(context);

            JSONObject jo = new JSONObject(response);
            String Status = jo.optString(AppStrings.OutputParams.Status);
            String Message = jo.optString(AppStrings.OutputParams.Message);
            if (Status.equals(AppStrings.OutputParams.Success)) {
                String Profile = jo.optString(AppStrings.OutputParams.Profile);


                sessionManager.setStoreData(AppStrings.Session.profile, "");
                sessionManager.setStoreData(AppStrings.Session.profile, Profile);


            } else {
//                AppMethods.alertWithOk(this, Message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getDateForFile() {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("dd_MM_yyyy");
        String formattedDate = df.format(c.getTime());
//        logAppUtils(TAG, "getDate: Current Date => " + formattedDate);
//        return formattedDate;

        String currentDateTimeString = "";
        try {
            currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return currentDateTimeString;
    }



   /* fun onBackPressed1(context: Context) {
        val intent = Intent()
        intent.action = Intent.ACTION_MAIN
        intent.addCategory(Intent.CATEGORY_HOME)
        context.startActivity(intent)
    }*/

  /*  public static void onBackPressed(Context context) {
        Intent i = new Intent();
        i.getAction(Intent.);
        i.addCategory(Intent.CATEGORY_HOME);
        context.startActivity(i);


    }*/

}
