package com.cpm.lorealbaautomation.constant;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;

import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.firebase.crashlytics.FirebaseCrashlytics;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster;
import com.cpm.lorealbaautomation.retrofit.DownloadAllDatawithRetro;
import com.cpm.lorealbaautomation.upload.UploadKeyData;

import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

import io.github.memfis19.annca.Annca;
import io.github.memfis19.annca.internal.configuration.AnncaConfiguration;

/**
 * Created by jeevanp on 2/16/2017.
 */

public class CommonFunctions {
    public static boolean checkNetIsAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    public static boolean isValidEmail(CharSequence target) {
        return !TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches();
    }

    public static void startAnncaCameraActivity(final Context context, final String path, Fragment fragment, final boolean showGrid, final int cameraFace) {
        if (context != null) {
            final AnncaConfiguration.Builder dialogDemo = getBuilder((Activity) context, fragment, cameraFace);
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.view_horizontal_camera);
            dialog.setCancelable(false);
            if (!dialog.isShowing()) {
                dialog.show();
            }
            new Handler().postDelayed(() -> {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                new Annca(dialogDemo.build()).launchCamera(path, showGrid, cameraFace);
            }, 1000);
        }

    }

    private static AnncaConfiguration.Builder getBuilder(Activity context, Fragment fragment, int cameraFace) {
        final AnncaConfiguration.Builder dialogDemo;
        if (fragment == null) {
            dialogDemo = new AnncaConfiguration.Builder(context, CommonString.CAPTURE_MEDIA);
        } else {
            dialogDemo = new AnncaConfiguration.Builder(fragment, CommonString.CAPTURE_MEDIA);
        }
        dialogDemo.setMediaAction(AnncaConfiguration.MEDIA_ACTION_PHOTO);
        dialogDemo.setCameraFace(cameraFace);
        dialogDemo.setMediaResultBehaviour(AnncaConfiguration.PREVIEW);
        return dialogDemo;
    }

    public static void setScaledImage(ImageView imageView, final String path) {
        final ImageView iv = imageView;
        ViewTreeObserver viewTreeObserver = iv.getViewTreeObserver();
        viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                iv.getViewTreeObserver().removeOnPreDrawListener(this);
                int imageViewHeight = iv.getMeasuredHeight();
                int imageViewWidth = iv.getMeasuredWidth();
                iv.setImageBitmap(decodeSampledBitmapFromPath(path, imageViewWidth, imageViewHeight));
                return true;
            }
        });
    }

    private static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth, int reqHeight) {
        // First decode with inJustDecodeBounds = true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        //BitmapFactory.decodeResource(res, resId, options);
        BitmapFactory.decodeFile(path, options);
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, options);
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image_icon
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    public static String getCurrentTimeHHMMSS() {
        Calendar m_cal = Calendar.getInstance();
        return m_cal.get(Calendar.HOUR_OF_DAY) + "" + m_cal.get(Calendar.MINUTE) + "" + m_cal.get(Calendar.SECOND);
    }


    public static String setMetadataAtImages(String store_Nm, String store_Id, String type, String userId) {
        return "Store Name : " + store_Nm + " | Store Id : " + store_Id + " " + " | Merchandiser Id : " + userId + " | Image Type : " + type;
    }


    public static String setMetadataAtImagesforwindow(String store_Nm, String store_Id, String window_cd, String type, String userId) {
        return "Store Name : " + store_Nm + " | Store Id : " + store_Id + " " + " | Window Id : " + window_cd + " | Merchandiser Id : " + userId + " | Image Type : " + type;
    }

    public static String setMetadataAtImagesforvisitorstorewise(String store_Nm, String store_Id, String visitor_nm, String type, String userId) {
        return "Store Name : " + store_Nm + " | Store Id : " + store_Id + " " + " | Visitor Name : " + visitor_nm + " | Merchandiser Id : " + userId + " | Image Type : " + type;
    }

    public static String setMetadataAtImagesforvisitor(String visitor_nm, String type, String userId) {
        return "Visitor Name : " + visitor_nm + " | Merchandiser Id : " + userId + " | Image Type : " + type;
    }

    public static String setMetadataAtImagesdpreporting(String type, String userId) {
        String ss = "Merchandiser Id : " + userId + " | Image Type : " + type;
        return ss;
    }


    public static Bitmap addMetadataAndTimeStampToImage(Context context, final String path, String metadata, String visit_date) {
        Bitmap bmp1 = BitmapFactory.decodeFile(path);
        @SuppressLint("InflateParams") View view = LayoutInflater.from(context).inflate(R.layout.preview_image, null);
        view.layout(0, 0, bmp1.getWidth(), bmp1.getHeight());
        Bitmap bmp = getViewBitmap(view, bmp1, path, metadata, visit_date);
        try {
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(path)));
            return bmp;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.fillInStackTrace();
            FirebaseCrashlytics.getInstance().recordException(e);
            return bmp1;
        }
    }

    @SuppressLint("SetTextI18n")
    public static Bitmap getViewBitmap(View view, Bitmap bmp, String path, String metadata, String visit_date) {
        //Get the dimensions of the view so we can re-layout the view at its current size
        @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
        String dateTime = sdf.format(Calendar.getInstance().getTime());
        String copm = dateTime;
        ImageView temp_img = (ImageView) view.findViewById(R.id.temp_img);
        TextView storeM = (TextView) view.findViewById(R.id.storeM);
        int copleteValue = 0;
        try {
            copm = copm.replaceAll("[- ]", " ");
            String[] items = copm.split(":");
            String seconds = items[2];
            int lastIndex;
            lastIndex = Integer.parseInt(seconds);
            int day = Integer.parseInt(visit_date.substring(3, 5));
            int a = Integer.parseInt("10") * Integer.parseInt("40");
            a = a + day;
            lastIndex = lastIndex * 2;
            copleteValue = a + lastIndex;
        } catch (NumberFormatException e) {
            FirebaseCrashlytics.getInstance().recordException(e);
            e.fillInStackTrace();
        }

        //timestamp on image_icon
        Bitmap dest = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas cs = new Canvas(dest);
        Paint tPaint = new Paint();
        tPaint.setTextSize(27);
        tPaint.setColor(Color.RED);
        tPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        cs.drawBitmap(bmp, 0f, 0f, null);
        float height_ = tPaint.measureText("yY");
        cs.drawText(dateTime + "[" + "10" + "] " + (copleteValue), 20f, height_ + 15f, tPaint);
        try {
            dest.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(path)));
        } catch (FileNotFoundException e) {
            FirebaseCrashlytics.getInstance().recordException(e);
            // TODO Auto-generated catch block
            e.fillInStackTrace();
        }

        storeM.setText(metadata + " | Date : " + dateTime + "[" + "10" + "] " + (copleteValue));
        bmp = BitmapFactory.decodeFile(path);
        temp_img.setImageBitmap(bmp);
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
        //Cause the view to re-layout
        view.measure(measuredWidth, measuredHeight);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        //Create a bitmap backed Canvas to draw the view into
        Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        view.draw(c);
        return b;
    }

    public static String getCurrentTime() {
        Calendar calendar = Calendar.getInstance();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
        return mdformat.format(calendar.getTime());
    }

    public static String getCurrentTime_only() {
        Calendar calendar = Calendar.getInstance();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
        return mdformat.format(calendar.getTime());
    }

    public static String getUUID(Context context) {
        SharedPreferences preferences = PrefHelper.getPrefs(context);
        String counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        return counter_id + "_" + UUID.randomUUID().toString();
    }

    public static boolean isTablet(Context context) {
        boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
        boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
        return (xlarge || large);
    }

    public static void show_image_preview(Context context, String img_name) {
        final Bitmap bmp = BitmapFactory.decodeFile(CommonString.getImagesFolder(context) + img_name);
        final Dialog dialog = new Dialog(context);
        //setting custom layout---------------------------- to dialog
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.custom_dialog_preview);
        Button cancel_btn = (Button) dialog.findViewById(R.id.cancel_btn);
        ImageView img_addit = (ImageView) dialog.findViewById(R.id.img_addit);
        img_addit.setImageBitmap(bmp);
        cancel_btn.setOnClickListener(v -> dialog.dismiss());
        dialog.show();
    }

    public static String convert24to12(String loginTym) {
        String strTym = "";
        try {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDate = new SimpleDateFormat("HH");
            Date date = simpleDate.parse(loginTym);
            assert date != null;
            simpleDate.format(date);
            Calendar calander = Calendar.getInstance();
            @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh");
            strTym = simpleDateFormat.format(calander.getTime());
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return strTym;
    }

    public static String setTimeFormat(String start_dt) {
        //test("xxxd" + start_dt);
        String newvalue = "";
        try {
            if (!start_dt.isEmpty()) {
                String s[] = start_dt.split(":");
                //test("time-----------------" + s[0] + "parseint" + Integer.parseInt(s[0]));
                int t = Integer.parseInt(s[0]);
                //test("vv....." + t);
                if (t < 12) {
                    s[0] = Integer.valueOf(s[0]).toString();
                    if (Integer.parseInt(s[0]) < 10 && s[0].length() == 0) {
                        newvalue = "0" + s[0] + ":" + s[1] + ":" + s[2];
                    } else {
                        newvalue = s[0] + ":" + s[1] + ":" + s[2];
                    }
                    //test("value..." + newvalue);
                } else {
                    int time = Integer.parseInt(s[0]) - 12;
                    if (time < 10) {
                        newvalue = "0" + time + ":" + s[1] + ":" + s[2];
                    } else {
                        newvalue = "0" + time + ":" + s[1] + ":" + s[2];
                    }

                    //test("value..." + newvalue);
                }
            }
        } catch (NumberFormatException e) {
            e.fillInStackTrace();
        }

        return newvalue;
    }

    public static File saveBitmapToFile(File file) {
        File file2 = file;
        try {
            int inWidth = 0;
            int inHeight = 0;
            InputStream in = new FileInputStream(file2);
            // decode image size (decode metadata only, not the whole image)
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, options);
            in.close();
            in = null;
            // save width and height
            inWidth = options.outWidth;
            inHeight = options.outHeight;
            // decode full image pre-resized
            in = new FileInputStream(file2);
            options = new BitmapFactory.Options();
            // calc rought re-size (this is no exact resize)
            options.inSampleSize = Math.max(inWidth / 800, inHeight / 500);
            // decode full image
            Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);
            if (roughBitmap == null) {
                return null;
            }
            // calc exact destination size
            Matrix m = new Matrix();
            RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
            RectF outRect = new RectF(0, 0, 800, 500);
            m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
            float[] values = new float[9];
            m.getValues(values);
            // resize bitmap
            Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);
            // save image
            try {
                FileOutputStream out = new FileOutputStream(file2);
                resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            } catch (Exception e) {
                //test("Image", e.toString(), e);
            }
        } catch (IOException e) {
            //test("Image", e.toString(), e);
            return file2;
        }
        return file;
    }

    public static Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = 0, height = 0;
        try {
            if (image != null) {
                width = image.getWidth();
                height = image.getHeight();

                if (maxSize != 0 && width != 0 && height != 0) {
                    float bitmapRatio = (float) width / (float) height;
                    if (bitmapRatio > 1) {
                        width = maxSize;
                        height = (int) (width / bitmapRatio);
                    } else {
                        height = maxSize;
                        width = (int) (height * bitmapRatio);
                    }
                }

            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        assert image != null;
        return Bitmap.createScaledBitmap(image, width, height, true);
    }

    public static Bitmap getCroppedBitmap(Bitmap bitmap) {
        Bitmap output = null;

        try {
            if (bitmap != null) {
                if (bitmap.getWidth() > bitmap.getHeight()) {
                    output = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
                } else {
                    output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getWidth(), Bitmap.Config.ARGB_8888);
                }

                Canvas canvas = new Canvas(output);
                final int color = 0xff424242;
                final Paint paint = new Paint();
                final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

                float r = 0;
                if (bitmap.getWidth() > bitmap.getHeight()) {
                    r = (float) bitmap.getHeight() / 2;
                } else {
                    r = (float) bitmap.getWidth() / 2;
                }
                paint.setAntiAlias(true);
                canvas.drawARGB(0, 0, 0, 0);
                paint.setColor(color);
                canvas.drawCircle(r, r, r, paint);
                paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
                canvas.drawBitmap(bitmap, rect, rect, paint);

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

        return output;
    }

    @SuppressLint("SetTextI18n")
    public static void show_incurrect_device_tym(final Context context, String serverTym) {
        if (context != null) {
            final Dialog dialog = new Dialog(context);
            //setting custom layout---------------------------- to dialog
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.dialog_incurrect_tym);
            dialog.setCancelable(false);
            Button cancel_btn = (Button) dialog.findViewById(R.id.cancel_btn);
            TextView txt_serverTym = (TextView) dialog.findViewById(R.id.txt_serverTym);
            txt_serverTym.setText("Server Time : " + serverTym);

            cancel_btn.setOnClickListener(v -> {
                context.startActivity(new Intent(android.provider.Settings.ACTION_DATE_SETTINGS));
                dialog.dismiss();
            });
            dialog.show();
        }
    }

    public static void delete_old_imge_from_folder(Context context, String visit_date, Lorealba_Database db) {
        db.open();
        try {
            if (db.CheckPreviousProduct(visit_date)) {
                File f = new File(CommonString.getImagesFolder(context));
                final File[] file = f.listFiles();
                if (file != null && file.length > 0) {
                    String filename = "";
                    for (File value : file) {
                        filename = value.getName();
                        if (filename.contains("_counter_img_one_") || filename.contains("_counter_img_two_") || filename.contains("_cp_img_one_") || filename.contains("_cp_img_two_") || filename.contains("_groomed_img_mrng_") || filename.contains("_groomed_img_noon_") || filename.contains("_groomed_img_evning_")) {
                            File originalFile = new File(CommonString.getImagesFolder(context) + value.getName());
                            if (originalFile.isFile() && originalFile.exists())
                                originalFile.delete();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public static void GetServerTym(Context context, String user_name, Lorealba_Database db) {
        try {
            ArrayList<String> keysList = new ArrayList<>();
            ArrayList<String> jsonList = new ArrayList<>();
            ArrayList<String> KeyNames = new ArrayList<>();
            keysList.add("ServerTime");
            for (int i = 0; i < keysList.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("Downloadtype", keysList.get(i));
                jsonObject.put("Username", user_name);
                jsonObject.put("Param1", "");
                jsonObject.put("Param2", "");
                jsonList.add(jsonObject.toString());
                KeyNames.add(keysList.get(i));
            }

            if (!jsonList.isEmpty()) {
                ProgressDialog pd = new ProgressDialog(context);
                DownloadAllDatawithRetro downloadData = new DownloadAllDatawithRetro(context, db, pd, CommonString.TAG_FROM_CURRENT);
                downloadData.listSize = jsonList.size();
                downloadData.downloadDataUniversalBa(jsonList, KeyNames, 0, CommonString.DOWNLOAD_ALL_SERVICE);
            }

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


    public static String removeFirstChar(String s) {
        String str = "";
        try {
            str = s.substring(1);
        } catch (Exception e) {
            e.fillInStackTrace();
            return str;
        }

        return str;
    }

    public static void call_upload(Context context) {
        if (checkNetIsAvailable(context)) {
            context.startActivity(new Intent(context, UploadKeyData.class).putExtra(CommonString.TAG_OBJECT, "1"));
        }
    }

    public static boolean checkincomplete_upload_data(String visit_date, String counter_id, Lorealba_Database db, boolean previous_date) {
        boolean status = true;
        try {
            if (!db.getBaProfileListData(visit_date, counter_id, previous_date).isEmpty()) {
                status = false;
            } else if (!db.getCounterProfileListData(visit_date, counter_id, previous_date).isEmpty()) {
                status = false;
            } else if (!db.getme_quiz_from(visit_date, counter_id, previous_date).isEmpty()) {
                status = false;
            } else if (!db.getgroomingdata(counter_id, visit_date, previous_date).isEmpty()) {
                status = false;
            } else if (!db.getba_counterimgList(counter_id, visit_date, previous_date).isEmpty()) {
                status = false;
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return status;
    }

    public static String removed_special_char(EditText common_edt) {
        String value_edt = "";
        try {
            if (common_edt.getText().toString().contains("[/;(!@#$%^&*?)\"]")) {
                value_edt = common_edt.getText().toString().trim().replaceAll("[/;(!@#$%^&*?)\"]", "");
            } else {
                value_edt = common_edt.getText().toString().trim();
            }

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

        return value_edt;
    }

    public static int mod(int x, int y) {
        int result = 0;
        try {
            result = x % y;
            if (result < 0) result += y;
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return result;
    }


    public String getCountOfDays(String fromDate, String toDate) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.getDefault());
        Date createdConvertedDate = null, expireCovertedDate = null, todayWithZeroTime = null;
        try {
            createdConvertedDate = dateFormat.parse(fromDate);
            expireCovertedDate = dateFormat.parse(toDate);

            Date today = new Date();

            todayWithZeroTime = dateFormat.parse(dateFormat.format(today));
        } catch (ParseException e) {
            e.fillInStackTrace();
        }

        int cYear = 0, cMonth = 0, cDay = 0;

        assert createdConvertedDate != null;
        if (createdConvertedDate.after(todayWithZeroTime)) {
            Calendar cCal = Calendar.getInstance();
            cCal.setTime(createdConvertedDate);
            cYear = cCal.get(Calendar.YEAR);
            cMonth = cCal.get(Calendar.MONTH);
            cDay = cCal.get(Calendar.DAY_OF_MONTH);

        } else {
            Calendar cCal = Calendar.getInstance();
            assert todayWithZeroTime != null;
            cCal.setTime(todayWithZeroTime);
            cYear = cCal.get(Calendar.YEAR);
            cMonth = cCal.get(Calendar.MONTH);
            cDay = cCal.get(Calendar.DAY_OF_MONTH);
        }

        Calendar eCal = Calendar.getInstance();
        assert expireCovertedDate != null;
        eCal.setTime(expireCovertedDate);

        int eYear = eCal.get(Calendar.YEAR);
        int eMonth = eCal.get(Calendar.MONTH);
        int eDay = eCal.get(Calendar.DAY_OF_MONTH);

        Calendar date1 = Calendar.getInstance();
        Calendar date2 = Calendar.getInstance();

        date1.clear();
        date1.set(cYear, cMonth, cDay);
        date2.clear();
        date2.set(eYear, eMonth, eDay);

        long diff = date2.getTimeInMillis() - date1.getTimeInMillis();

        float dayCount = (float) diff / (24 * 60 * 60 * 1000);

        return ((int) dayCount + " Days");
    }

    public static void hideKeyboard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        //Find the currently focused view, so we can grab the correct window token from it.
        View view = activity.getCurrentFocus();
        //If no view currently has focus, create a new one, just so we can grab a window token from it
        if (view == null) {
            view = new View(activity);
        }
        if (imm.isAcceptingText()) imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public static String capitalizeFirstLetter(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        return input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase();
    }

    public static void dismissKeyboard(View view) {
        try {
            if (view != null) {
                InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static ArrayList<ProductMaster> getFilters() {
        ArrayList<ProductMaster> listSubAxe = new ArrayList<>();
        try {
            ProductMaster obj = new ProductMaster();
            obj.setSubAxeName("Axe");
            listSubAxe.add(obj);

            obj = new ProductMaster();
            obj.setSubAxeName("Sub Axe");
            listSubAxe.add(obj);

            obj = new ProductMaster();
            obj.setSubAxeName("Signature");
            listSubAxe.add(obj);

            obj = new ProductMaster();
            obj.setSubAxeName("Sub Brand");
            listSubAxe.add(obj);

            obj = new ProductMaster();
            obj.setSubAxeName("Brand");
            listSubAxe.add(obj);

            obj = new ProductMaster();
            obj.setSubAxeName("Product");
            listSubAxe.add(obj);
        } catch (Exception ignored) {
        }

        return listSubAxe;
    }

    public static String formatDate(String inputDate) {
        // Check if the device supports java.time (API 26+)
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            // Input date format (MM/dd/yyyy)
            DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.ENGLISH);
            // Desired output date format (MMMM dd, yyyy)
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MMM dd, yyyy", Locale.ENGLISH);

            // Parse the input date string
            LocalDate date = LocalDate.parse(inputDate, inputFormatter);

            // Return formatted date
            return date.format(outputFormatter);

        } else {
            // For older Android versions (below API 26)
            SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
            SimpleDateFormat outputFormat = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH);
            try {
                // Parse the input date string
                Date date = inputFormat.parse(inputDate);
                // Format the date to the desired output
                assert date != null;
                return outputFormat.format(date);
            } catch (ParseException e) {
                e.fillInStackTrace();
                return null; // Return null if parsing fails
            }
        }
    }
}
