package com.cygnusa.hyperm.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.fragment.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

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

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.ResponseBody;

import static android.content.Context.INPUT_METHOD_SERVICE;


public class CommonMethods {

    //In this Permissions array you can add as many permissions you want and handle at a time.
    @SuppressLint("InlinedApi")
    public static String[] PERMISSIONS = {
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAPTURE_AUDIO_OUTPUT,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_COARSE_LOCATION

    };
    private static StorePreference storePreference;
    private Context context;
    public static Toast toast;

    public CommonMethods(Context context) {
        this.context = context;
        storePreference = new StorePreference(context);
    }


    public static boolean checkNullForAll(String state) {
        return state != null;
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        assert connectivityManager != null;
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
    }

    public static String getConvertDateFormat(String date) {


        SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");

        Date myDate = null;
        try {
            myDate = dateFormat.parse(date);

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

        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
        String finalDate = timeFormat.format(myDate);

        System.out.println(finalDate);
        return finalDate;
    }

    public static String getConvertDateFormatReverse(String date) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date myDate = null;
        try {
            myDate = dateFormat.parse(date);

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

        SimpleDateFormat timeFormat = new SimpleDateFormat("MMM dd, yyyy");
        String finalDate = timeFormat.format(myDate);

        System.out.println(finalDate);
        return finalDate;
    }

    public static String getConvertDateStringFormat(String date) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy  hh:mm aaa");

        Date myDate = null;
        try {
            myDate = dateFormat.parse(date);

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

        //SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");

        return dateFormat.format(myDate);
    }

    @SuppressLint("ShowToast")
    public static Toast showToast(Context activity, String msg) {
        try {
            toast.cancel();
        } catch (Exception e) {
            e.printStackTrace();
        }
        toast = Toast.makeText(activity, msg, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        return toast;
    }

    public static Bitmap getResizedBitmap(Bitmap image, int maxSize) {

        int width = image.getWidth();
        int height = image.getHeight();
        float bitmapRatio = (float) width / (float) height;
        if (bitmapRatio > 0) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        }
        return Bitmap.createScaledBitmap(image, width, height, true);
    }

    public static String getFilepathFromBitmap(FragmentActivity activity, Bitmap bitmap, Intent intent, String filePath1) {

        String getFilePathFromBitmap = "";
        File fileGetFromBitmap;
        if (Build.VERSION.SDK_INT > 24) {
            if (intent != null) {
                Uri tempUri = intent.getData();
                if (tempUri != null) {
                    File getRealFilePath = new File(getRealPathFromURI(activity, tempUri));
                    getFilePathFromBitmap = getRealFilePath.getAbsolutePath();
                } else {
                    getFilePathFromBitmap = filePath1;
                }
            } else {
                Uri tempUri = getImageUri(activity, bitmap);
                File getRealFilePath = new File(getRealPathFromURI(activity, tempUri));
                getFilePathFromBitmap = getRealFilePath.getAbsolutePath();
            }
        } else {
            if (intent != null) {
                Uri tempUriSample = getImageUri(activity, bitmap);
                if (getRealPathFromURI(activity, tempUriSample) != null) {
                    fileGetFromBitmap = new File(getRealPathFromURI(activity, tempUriSample));
                    getFilePathFromBitmap = fileGetFromBitmap.getAbsolutePath();
                } else {
                    Uri tempUri = getImageUri(activity, bitmap);
                    File getRealFilePath = new File(getRealPathFromURI(activity, tempUri));
                    getFilePathFromBitmap = getRealFilePath.getAbsolutePath();
                }
            } else {
                Uri tempUri = getImageUri(activity, bitmap);
                File getRealFilePath = new File(getRealPathFromURI(activity, tempUri));
                getFilePathFromBitmap = getRealFilePath.getAbsolutePath();
            }
        }
        Log.d("ORIGINAL FILE", "" + getFilePathFromBitmap);
        return getFilePathFromBitmap;
    }


    public static String getRealPathFromURI(Activity activity, Uri uri) {
        Cursor cursor = activity.getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(idx);
    }


    public static Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

    public static String getFilepathFromGallery(Activity activity, Bitmap bitmap, Intent intent, String selectedImagePath) {

        String getFilePathFromBitmap = "";
        File fileGetFromBitmap;
        if (Build.VERSION.SDK_INT > 24) {
            if (intent != null) {
                Uri tempUri = intent.getData();
                if (tempUri != null) {
                    if (getRealPathFromURI(activity, tempUri) != null) {
                        File getRealFilePath = new File(getRealPathFromURI(activity, tempUri));
                        getFilePathFromBitmap = getRealFilePath.getAbsolutePath();
                    } else {
                        getFilePathFromBitmap = "Invalid File";
                    }
                } else {
                    getFilePathFromBitmap = selectedImagePath;
                }
            } else {
                Uri tempUri = getImageUri(activity, bitmap);
                File getRealFilePath = new File(getRealPathFromURI(activity, tempUri));
                getFilePathFromBitmap = getRealFilePath.getAbsolutePath();
            }
        } else {
            if (intent != null) {
                Uri tempUriSample = intent.getData();
                if (tempUriSample != null) {
                    fileGetFromBitmap = new File(getRealPathFromURI(activity, tempUriSample));
                    getFilePathFromBitmap = fileGetFromBitmap.getAbsolutePath();
                } else {
                    Uri tempUri = getImageUri(activity, bitmap);
                    File getRealFilePath = new File(getRealPathFromURI(activity, tempUri));
                    getFilePathFromBitmap = getRealFilePath.getAbsolutePath();
                }
            } else {
                Uri tempUri = getImageUri(activity, bitmap);
                File getRealFilePath = new File(getRealPathFromURI(activity, tempUri));
                getFilePathFromBitmap = getRealFilePath.getAbsolutePath();
            }
        }
        return getFilePathFromBitmap;
    }

    public static void hideKeyboard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(INPUT_METHOD_SERVICE);
        assert imm != null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            imm.hideSoftInputFromWindow(Objects.requireNonNull(activity.getCurrentFocus()).getWindowToken(), 0);
        }
    }

    public static int getBitmapSize(Bitmap data) {

        return data.getByteCount();
    }

    public static void errorShow(Context activity, ResponseBody response) {
        StorePreference storePreference;
        storePreference = new StorePreference(activity);
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(response.string());
            String message = "";
            if (jsonObject.getString("message") != null) {
                message = jsonObject.getString("message");
            } else {
                message = jsonObject.getString("response_text");
            }

            if (message != null)
                CommonMethods.showToast(activity, message).show();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getPhotoFileUri(Activity activity, String fileName) {

        // Only continue if the SD Card is mounted
        if (isExternalStorageAvailable()) {
            File mediaStorageDir = new File(activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "Medpal");
            if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) {
            }
            return new File(mediaStorageDir.getPath() + File.separator + fileName + ".jpg").getAbsolutePath();
        }
        return null;
    }

    private static boolean isExternalStorageAvailable() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    public static void trustManager() throws Exception {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        tmf.init((KeyStore) null);

        TrustManager[] trustManagers = tmf.getTrustManagers();
        final X509TrustManager origTrustmanager = (X509TrustManager) trustManagers[0];

        TrustManager[] wrappedTrustManagers = new TrustManager[]{
                new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return origTrustmanager.getAcceptedIssuers();
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
                        origTrustmanager.checkClientTrusted(certs, authType);
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }
                }
        };

        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, wrappedTrustManagers, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }
}
