package cpm.com.gskmtorange.constant;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.view.ViewTreeObserver;
import android.widget.ImageView;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import android.app.AlertDialog;

import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.interfaces.DialogCallbackListener;

/**
 * Created by yadavendras on 13-11-2017.
 */

public class CommonFunctions {
    public static boolean updateLangResources(Context context, String language) {
        String lang;
        if (language.equalsIgnoreCase(CommonString.KEY_LANGUAGE_ENGLISH)) {
            lang = CommonString.KEY_RETURE_LANGUAGE_ENGLISH;
        } else if (language.equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_KSA)) {
            lang = CommonString.KEY_RETURE_LANGUAGE_ARABIC_KSA;
        } else if (language.equalsIgnoreCase(CommonString.KEY_LANGUAGE_TURKISH)) {
            lang = CommonString.KEY_RETURE_LANGUAGE_TURKISH;
        } else if (language.equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_UAE)) {
            lang = CommonString.KEY_RETURE_LANGUAGE_UAE_ARABIC;
        } else if (language.equalsIgnoreCase(CommonString.KEY_LANGUAGE_OMAN)) {
            lang = CommonString.KEY_RETURE_LANGUAGE_OMAN;
        } else if (language.equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_EGYPT)) {
            lang = CommonString.KEY_RETURN_LANGUAGE_EGYPT;
        } else if (language.equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_JORDAN)) {
            lang = CommonString.KEY_RETURE_LANGUAGE_ARABIC_KSA;
        } else if (language.equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_KUWAIT)) {
            lang = CommonString.KEY_RETURE_LANGUAGE_ARABIC_KSA;
        } else if (language.equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_BAHRAIN)) {
            lang = CommonString.KEY_RETURE_LANGUAGE_ARABIC_KSA;
        } else if (language.equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_OMAN)) {
            lang = CommonString.KEY_RETURE_LANGUAGE_ARABIC_KSA;
        } else if (language.equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_QATAR)) {
            lang = CommonString.KEY_RETURE_LANGUAGE_ARABIC_KSA;
        } else if (language.equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_LIBIYA)) {
            lang = CommonString.KEY_RETURE_LANGUAGE_ARABIC_KSA;
        } else if (language.equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_LEBANON)) {
            lang = CommonString.KEY_RETURE_LANGUAGE_ARABIC_KSA;
        } else {
            lang = CommonString.KEY_RETURN_LANGUAGE_DEFAULT;
        }
        Locale locale = new Locale(lang);
        Locale.setDefault(locale);
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        return true;
    }

    public static String getCurrentTimeWithLanguage(Context context) {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        Calendar m_cal = Calendar.getInstance();
        String cdate = formatter.format(m_cal.getTime());
        //SharedPreferences preferences = preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        if (preferences.getString(CommonString.KEY_LANGUAGE, "").equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_KSA)
                ////aDDED NEW COUNTRY FOR TIME BY JP
                || preferences.getString(CommonString.KEY_LANGUAGE, "").equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_KUWAIT)
                || preferences.getString(CommonString.KEY_LANGUAGE, "").equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_BAHRAIN)
                || preferences.getString(CommonString.KEY_LANGUAGE, "").equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_OMAN)
                || preferences.getString(CommonString.KEY_LANGUAGE, "").equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_QATAR)
                || preferences.getString(CommonString.KEY_LANGUAGE, "").equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_LEBANON)
                || preferences.getString(CommonString.KEY_LANGUAGE, "").equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_LIBIYA)
                || preferences.getString(CommonString.KEY_LANGUAGE, "").equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_UAE)
                || preferences.getString(CommonString.KEY_LANGUAGE, "").equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_JORDAN)
                || preferences.getString(CommonString.KEY_LANGUAGE, "").equalsIgnoreCase(CommonString.KEY_LANGUAGE_ARABIC_EGYPT)) {
            cdate = arabicToenglish(cdate);
        }
        return cdate;
    }

    private static String arabicToenglish(String number) {
        char[] chars = new char[number.length()];
        for (int i = 0; i < number.length(); i++) {
            char ch = number.charAt(i);
            if (ch >= 0x0660 && ch <= 0x0669)
                ch -= 0x0660 - '0';
            else if (ch >= 0x06f0 && ch <= 0x06F9)
                ch -= 0x06f0 - '0';
            chars[i] = ch;
        }
        return new String(chars);
    }

    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
        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 void showAlertDialog(final Context context, String msg) {
        final DialogCallbackListener[] mListener = new DialogCallbackListener[1];
        try {
            // Instantiate the NoticeDialogListener so we can send events to the host
            mListener[0] = (DialogCallbackListener) context;
        } catch (ClassCastException e) {
            Activity activity = (Activity) context;
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.getClass() + " must implement DialogCallbackListener");
        }
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        alertDialogBuilder.setTitle(context.getResources().getString(R.string.dialog_title));
        // set dialog message
        alertDialogBuilder.setMessage(msg)
                .setCancelable(false)
                .setPositiveButton(context.getResources().getString(R.string.yes), (dialog, id) -> {
                    mListener[0].onSelect(true);
                    dialog.cancel();
                }).setNegativeButton(context.getResources().getString(R.string.no), (dialog, id) -> {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    mListener[0].onSelect(false);
                    dialog.cancel();
                });
        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();
        // show it
        alertDialog.show();
    }

    public static void savefile(Uri sourceuri, String _path) {
        String sourceFilename = sourceuri.getPath();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(sourceFilename));
            bos = new BufferedOutputStream(new FileOutputStream(_path, false));
            byte[] buf = new byte[1024];
            bis.read(buf);
            do {
                bos.write(buf);
            } while (bis.read(buf) != -1);
        } catch (IOException e) {
            e.fillInStackTrace();
        } finally {
            try {
                if (bis != null) bis.close();
                if (bos != null) bos.close();
            } catch (IOException e) {
                e.fillInStackTrace();
            }
        }
    }
}
