package kr.co.hanwha.hifive.util;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import java.util.UUID;

import kr.co.hanwha.hifive.data.model.UpdateData;

/**
 * Created by sanghoonkwon on 2018. 1. 10..
 */

public class HFCommonUtil {
    /**
     * Color 리소스를 가져온다.
     */
    public static final int getColor(Context context, int id) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 23) {
            return ContextCompat.getColor(context, id);
        } else {
            return context.getResources().getColor(id);
        }
    }

    /**
     * @param red
     * @param green
     * @param blue
     * @return RGB Color
     */
    public static final int getColor(int red, int green, int blue) {
        return Color.rgb(red, green, blue);
    }

    /**
     * Screen Width
     *
     * @param context Context
     * @return int
     */
    public static int getScreenWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * Screen Height
     *
     * @param context Context
     * @return int
     */
    public static int getScreenHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * Status Bar Height
     *
     * @param context Context
     * @return int
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * Dimension dp to pixel
     *
     * @param context  Context
     * @param dimenRes dimension resource id
     * @return Pixel
     */
    public static int getPixelFromDimension(Context context, int dimenRes) {
        return context.getResources().getDimensionPixelOffset(dimenRes);
    }

    public static float getPixelFromDp(Context context, float dp) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        float px = dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
        return px;
    }

    public static float getPixelFromSp(Context context, float sp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getResources().getDisplayMetrics());
    }
    /**
     * Tab 여박
     *
     * @param tabLayout
     * @param externalMargin
     * @param internalMargin
     * @param padding
     */
    public static void wrapTabIndicatorToTitle(TabLayout tabLayout, int externalMargin, int internalMargin, int padding) {
        View tabStrip = tabLayout.getChildAt(0);
        if (tabStrip instanceof ViewGroup) {
            ViewGroup tabStripGroup = (ViewGroup) tabStrip;
            int childCount = ((ViewGroup) tabStrip).getChildCount();
            for (int i = 0; i < childCount; i++) {
                View tabView = tabStripGroup.getChildAt(i);
                tabView.setMinimumWidth(0);
                tabView.setPadding(padding, tabView.getPaddingTop(), padding, tabView.getPaddingBottom());
                if (tabView.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
                    ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) tabView.getLayoutParams();
                    if (i == 0) {
                        settingMargin(layoutParams, externalMargin, internalMargin);
                    } else if (i == childCount - 1) {
                        settingMargin(layoutParams, internalMargin, externalMargin);
                    } else {
                        settingMargin(layoutParams, internalMargin, internalMargin);
                    }
                }
            }

            tabLayout.requestLayout();
        }
    }

    /**
     * Tab 여백
     *
     * @param layoutParams
     * @param start
     * @param end
     */
    private static void settingMargin(ViewGroup.MarginLayoutParams layoutParams, int start, int end) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            layoutParams.setMarginStart(start);
            layoutParams.setMarginEnd(end);
        } else {
            layoutParams.leftMargin = start;
            layoutParams.rightMargin = end;
        }
    }

    public static boolean checkUpdate(@NonNull Context context, UpdateData data) {
        if (data != null && data.getUpdateInfo() != null) {
            String appVersion = HFCommonUtil.getAppVersion(context);
            String lastVersion = data.getUpdateInfo().getVersion();
            return lastVersion.compareTo(appVersion) > 0;
        }
        return false;
    }

    /**
     * 클립보드에 복사
     *
     * @param context
     * @param message
     * @param toast
     */
    public static void copyClipboard(Context context, String message, String toast) {
        try {
            ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Clip", message);
            clipboard.setPrimaryClip(clip);
            if (toast != null && toast.length() > 0)
                Toast.makeText(context, toast, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**************************************************
     *
     *              Application Info
     *
     **************************************************/
    public static String getAppVersion(Context context) {
        String version = "0";
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            version = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    /**************************************************
     *
     *              Hardware Info
     *
     **************************************************/
    public static String getDeviceUUID(Context context) {
        String deviceId = "";
        try {
            deviceId = HFInfoUtil.getDeviceUUID(context);//6b359ffe-bb7c-4257-adaf-717a16274291
            if (TextUtils.isEmpty(deviceId)) {
                String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
                if (TextUtils.isEmpty(androidId) == false)
                    deviceId = androidId;
                else
                    deviceId = UUID.randomUUID().toString();
                HFInfoUtil.setDeviceUUID(context, deviceId);
            }
//            final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//            String tmDevice = tm.getDeviceId();
//            String tmSerial = tm.getSimSerialNumber();
//            String androidId = android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
//            UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
//            deviceId = deviceUuid.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return deviceId;
    }

    public static String getDeviceOsVersion() {
        try {
            return Build.VERSION.RELEASE;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getDeviceModelName() {
        try {
            return Build.MODEL;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
