package com.yono.messeripos.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.DividerItemDecoration;

import com.bumptech.glide.load.engine.Resource;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.yono.messeripos.R;
import com.yono.messeripos.adapter.CategoryAdapter;
import com.yono.messeripos.models.CategoryModels;

import java.io.ByteArrayOutputStream;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {

    public Utils(){};
    public Utils(View v){};

    public long grandTotal = 0;
    public static TextView btnCard;

    public interface DialogListener {
        void onClickDisimiss(AlertDialog alertDialog);
        void onClickLink(AlertDialog alertDialog);
    }

    private DialogListener listener;

    public void setListener(DialogListener listener) {
        this.listener = listener;
    }

    public String convertPrice(String mataUang, int nilai ){
        DecimalFormat rupiah = (DecimalFormat) DecimalFormat.getCurrencyInstance();
        DecimalFormatSymbols format = new DecimalFormatSymbols();

        format.setCurrencySymbol(mataUang);
        format.setMonetaryDecimalSeparator(',');
        format.setGroupingSeparator('.');

        rupiah.setDecimalFormatSymbols(format);

        return rupiah.format(nilai);
    }

    public String convertPrice(String mataUang, long nilai ){
        DecimalFormat rupiah = (DecimalFormat) DecimalFormat.getCurrencyInstance();
        DecimalFormatSymbols format = new DecimalFormatSymbols();

        format.setCurrencySymbol(mataUang);
        format.setMonetaryDecimalSeparator(',');
        format.setGroupingSeparator('.');

        rupiah.setDecimalFormatSymbols(format);

        return rupiah.format(nilai);
    }

    public String timeStamp(){
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        return  timeStamp;
    }

    public String dateNow(){
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    public String convertGson(Object object){
        String js = new Gson().toJson(object);
        return js;
    }

    public DividerItemDecoration dividerItemDecoration(Context context){
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
        return dividerItemDecoration;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public String convertDate(String date) throws ParseException {
//        DateTimeFormatter dateTimeFormatter =
//                DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'")
//                .withZone(ZoneId.of("UTC"));
//
//        LocalDateTime localDateTime = LocalDateTime
//                .parse(date, dateTimeFormatter);
//
//        DateTimeFormatter localFormatter = DateTimeFormatter
//                .ofPattern("EEEE, dd MM yyyy", new Locale("id", "ID"));
//        String localDate = localDateTime.format(localFormatter);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date tanggal = sdf.parse(date);
        SimpleDateFormat outputFormat = new SimpleDateFormat("EEEE, dd MM yyyy ", Locale.ENGLISH);
        outputFormat.setTimeZone(TimeZone.getTimeZone("Asia/Jakarta"));

        return outputFormat.format(tanggal);
    }

    public String convertImageBase64File(String pathname){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

//        BitmapFactory.Options options = new BitmapFactory.Options();
//        options.inJustDecodeBounds = true;
//        options.inSampleSize = 3;
//        options.inSampleSize = calculateInSampleSize(options, 20,20);

        Bitmap bitmap = BitmapFactory.decodeFile(pathname);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
        byte[] b = baos.toByteArray();
        String encodeImage = Base64.encodeToString(b, Base64.DEFAULT);
        Log.i("Count_encode", "convertImageBase64Resource: "+bitmap.getByteCount());

        return encodeImage;
    }

    public Toast toastMessage(Context context, String message){
        return Toast.makeText(context, message, Toast.LENGTH_LONG);
    }

    public String convertImageBase64Resource(Resources resource, int id){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] b = baos.toByteArray();

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inSampleSize = 3;
        options.inSampleSize = calculateInSampleSize(options, 500,500);

        Bitmap bitmap = BitmapFactory.decodeResource(resource, id, options);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
        String encodeImage = Base64.encodeToString(b, Base64.DEFAULT);
        Log.i("Count_encode", "convertImageBase64Resource: "+bitmap.getByteCount());
        return encodeImage;
    }

    public Bitmap decodeImageBase64(String source){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] imageBytes = baos.toByteArray();
        imageBytes = Base64.decode(source, Base64.DEFAULT);
        Bitmap decodeImages = BitmapFactory.decodeByteArray(imageBytes,0,imageBytes.length);
//        Bitmap bf = BitmapFactory.decodeFile(source, options);

//        Log.i("Size bitmap", "decodeImageBase64: "+decodeImages.getByteCount());
        return decodeImages;
    }

    public long grandTotalCart(){
        return grandTotal;
    }

    public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        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 Snackbar snackBar(View v, String message){
        Snackbar snackbar = Snackbar.make(v, message, Snackbar.LENGTH_LONG);
        return snackbar;
    }

    public boolean isValidEmail(String email) {
        String regex = "^(.+)@(.+)$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();

    }

    public boolean isValidPassword(String pass) {
        String regex = "^(?=.*[A-Za-z-0-9])(?=.*\\d)[A-Za-z-0-9\\d]{8,}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(pass);
        return matcher.matches();
    }
    /**
     * Alert Dialog
     * @param context
     * @param cancelable
     * @return
     */
    public AlertDialog dialog(Context context, Boolean cancelable) {

        final View view = View.inflate(context, R.layout.alert_dialog, null);

        CardView btnCard = view.findViewById(R.id.cvAlertOnClick);

        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setCancelable(cancelable)
                .setView(view);

        AlertDialog dialog = builder.create();
        dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
        btnCard.setOnClickListener(view1 -> listener.onClickDisimiss(dialog));
        return dialog;

    }

    public AlertDialog dialog(Context context,
                              Boolean cancelable,
                              @Nullable String titles) {

        final View view = View.inflate(context, R.layout.alert_dialog, null);

        TextView title = view.findViewById(R.id.alertTitles);
        CardView btnCard = view.findViewById(R.id.cvAlertOnClick);

//        set title and message
        if (titles != null){
            title.setText(titles);
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setCancelable(cancelable)
                .setView(view);

        AlertDialog dialog = builder.create();
        dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
        btnCard.setOnClickListener(view1 -> listener.onClickDisimiss(dialog));
        return dialog;

    }

    public AlertDialog dialog(Context context,
                              Boolean cancelable,
                              @Nullable String titles,
                              @Nullable String messages) {

        final View view = View.inflate(context, R.layout.alert_dialog, null);

        TextView title = view.findViewById(R.id.alertTitles);
        TextView message = view.findViewById(R.id.alertBody);
        CardView btCard = view.findViewById(R.id.cvAlertOnClick);

//        set title and message
        if (titles != null){
            title.setText(titles);
        }

        if (message != null){
            message.setText(messages);
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setCancelable(cancelable)
                .setView(view);

        AlertDialog dialog = builder.create();
        dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
        btCard.setOnClickListener(view1 -> listener.onClickDisimiss(dialog));
        return dialog;
    }

    public AlertDialog dialog(Context context,
                              Boolean cancelable,
                              @Nullable String titles,
                              @Nullable String messages,
                              @Nullable String dismiss) {

        final View view = View.inflate(context, R.layout.alert_dialog, null);

        TextView title = view.findViewById(R.id.alertTitles);
        TextView message = view.findViewById(R.id.alertBody);
        TextView button2 = view.findViewById(R.id.tvTextBtn2);
        CardView btnCard2 = view.findViewById(R.id.cvAlertOnClick2);


//        set title and message
        if (titles != null){
            title.setText(titles);
        }

        if (message != null){
            message.setText(messages);
        }

        if (button2 != null){
            btnCard2.setVisibility(View.VISIBLE);
            button2.setText(dismiss);
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setCancelable(cancelable)
                .setView(view);

        AlertDialog dialog = builder.create();
        dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
        btnCard2.setOnClickListener(view1 -> listener.onClickDisimiss(dialog));
        return dialog;

    }


    public AlertDialog dialog(Context context,
                              Boolean cancelable,
                              @Nullable String titles,
                              @Nullable String messages,
                              @Nullable String dismiss,
                              @Nullable String link) {

        /**
         * Button1 untuk dismiss
         * Button2 untuk link
         */

        final View view = View.inflate(context, R.layout.alert_dialog, null);

        TextView title = view.findViewById(R.id.alertTitles);
        TextView message = view.findViewById(R.id.alertBody);
        TextView button = view.findViewById(R.id.tvTextBtn);
        TextView button2 = view.findViewById(R.id.tvTextBtn2);
        CardView btnCard = view.findViewById(R.id.cvAlertOnClick);
        CardView btnCard2 = view.findViewById(R.id.cvAlertOnClick2);

//        set title and message
        title.setText(titles);
        message.setText(messages);

        btnCard.setVisibility(View.VISIBLE);
        button.setText(link);

        btnCard2.setVisibility(View.VISIBLE);
        button2.setText(dismiss);

        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setCancelable(cancelable)
                .setView(view);

        AlertDialog dialog = builder.create();
        dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;

        btnCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onClickLink(dialog);
            }
        });
        btnCard2.setOnClickListener(view1 -> listener.onClickDisimiss(dialog));
        return dialog;

    }

//    get window size
    public int getWindowHeight() {
        return Resources.getSystem().getDisplayMetrics().heightPixels;
    }
    public int getWindowWidth() {
        return Resources.getSystem().getDisplayMetrics().widthPixels;
    }
    public String getRandomNumberString() {
        // It will generate 6 digit random Number.
        // from 0 to 999999
        Random rnd = new Random();
        int number = rnd.nextInt(9999);

        // this will convert any number sequence into 6 character.
        return String.format("%04d", number);
    }
}
