package com.key.vibekeyboard.utils;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.inputmethodservice.Keyboard;
import android.util.TypedValue;

import com.key.vibekeyboard.inputmethod.view.CustomKeyboardView;

public class DrawableUtils {

    public static void drawKeyIcon(Keyboard.Key currentKey,
                                     Drawable drawKeyIcon,
                                     Canvas myCanvas,
                                     CustomKeyboardView customKeyboardView) {
        currentKey.icon = drawKeyIcon;
        currentKey.icon.setBounds(getIconBounds(currentKey, drawKeyIcon, customKeyboardView));
        currentKey.icon.draw(myCanvas);
    }

    private static Rect getIconBounds(Keyboard.Key currentKey,
                                            Drawable drawKeyIcon,
                                            CustomKeyboardView customKeyboardView) {
        float icon_w = drawKeyIcon.getIntrinsicWidth();
        float icon_h = drawKeyIcon.getIntrinsicHeight();
        float icon_wr = icon_w / currentKey.width;
        float icon_hr = icon_h / currentKey.height;

        float tep1, tep2;
        if (icon_wr > icon_hr) {
            tep2 = icon_wr;
            tep1 = Math.max(icon_wr, 0.5f);
        } else {
            tep2 = icon_hr;
            tep1 = Math.max(icon_hr, 0.5f);
        }

        icon_h = (icon_h / tep2) * tep1;
        icon_w = (icon_w / tep2) * tep1;

        int top = (int) (currentKey.y + customKeyboardView.getPaddingTop() + (currentKey.height - icon_h) / 2);
        int left = (int) (currentKey.x + customKeyboardView.getPaddingLeft() + (currentKey.width - icon_w) / 2);
        int bottom = top + (int) icon_h;
        int right = left + (int) icon_w;

        return new Rect(left, top, right, bottom);
    }

    public static float spToPx(Float values, Context context) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, values, context.getResources().getDisplayMetrics());
    }

}
