package com.seatel.mobilehall.util.customview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.seatel.mobilehall.R;
import com.seatel.mobilehall.util.AnimationUtil;
import com.seatel.mobilehall.util.interactor.KeyBoardNumberInteractor;

import org.jetbrains.annotations.NotNull;

import java.util.Objects;

public class CustomKeyboard extends FrameLayout implements View.OnClickListener, KeyBoardNumberInteractor.View, View.OnLongClickListener {

    private KeyBoardNumberInteractor keyBoardNumberInteractor;
    private EditText mEditText;
    private int mBackground;
    private SelectKeyListener mCallBackKeySelect;

    public void setmMaxLenght(int mMaxLenght) {
        this.mMaxLenght = mMaxLenght;
    }

    private int mMaxLenght;

    public CustomKeyboard(@NonNull Context context) {
        super(context);
    }

    public CustomKeyboard(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CustomKeyboard(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    public void setmCallBackKeySelect(SelectKeyListener callBack) {
        this.mCallBackKeySelect = callBack;
    }

    private void init(@NonNull Context context, @Nullable AttributeSet attrs) {

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomKeyboard);

        try {
            mBackground = a.getResourceId(R.styleable.CustomKeyboard_keyBackground, 0);
            if (mBackground == 0) mBackground = R.drawable.bg_button_grey;
        } finally {
            a.recycle();
        }

        DisplayMetrics displayMetrics = new DisplayMetrics();
        ((Activity) getContext()).getWindowManager()
                .getDefaultDisplay()
                .getMetrics(displayMetrics);

        int height = displayMetrics.heightPixels;
        int width = displayMetrics.widthPixels;

        float density = getResources().getDisplayMetrics().density;
        int keyBoardZone;
        if (density < 2) keyBoardZone = (int) (height * 0.32f);
        else keyBoardZone = (int) (height * 0.3f);

        createGrid(width, keyBoardZone);
    }

    @SuppressLint("ResourceType")
    private void createGrid(int gridWidth, int gridHeight) {

        int keyboardMargin = (int) getContext().getResources().getDimension(R.dimen.keyboard_margin);
        int keyDeletePadding = (int) getContext().getResources().getDimension(R.dimen.key_delete_padding);
        int keyMarginTop = (int) getContext().getResources().getDimension(R.dimen.key_margin_top);


        GridLayout gridLayout = new GridLayout(getContext());
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, gridHeight);
        gridLayout.setLayoutParams(layoutParams);
        gridLayout.setBackgroundColor(getContext().getResources().getColor(android.R.color.transparent));

        int height = (gridHeight - keyMarginTop - (getPaddingBottom() + getPaddingTop())) / 4;
        int width = (gridWidth - (keyboardMargin * 3) - (getPaddingStart() + getPaddingEnd())) / 3;

        int total = 12;
        int column = 3;
        int row = total / column;
        gridLayout.setAlignmentMode(GridLayout.ALIGN_BOUNDS);
        gridLayout.setColumnCount(column);
        gridLayout.setRowCount(row + 1);
        Button button;
        for (int i = 0, c = 0, r = 0; i < total; i++, c++) {
            if (c == column) {
                c = 0;
                r++;
            }

            if (i == 9) {
                View view = new View(getContext());
                GridLayout.LayoutParams param = new GridLayout.LayoutParams();
                gridLayout.addView(view, i);
                param.height = height;
                param.width = width;
                view.setLayoutParams(param);
            } else if (i == 11) {

                ImageView imageView = new ImageView(getContext());
                GridLayout.LayoutParams param = new GridLayout.LayoutParams();
                param.setGravity(Gravity.CENTER);
                imageView.setImageDrawable(getContext().getResources().getDrawable(R.drawable.key_board_clear_selector));
                gridLayout.addView(imageView, i);
                param.height = height - keyDeletePadding;
                param.width = width - keyDeletePadding;
                imageView.setLayoutParams(param);
                imageView.setOnClickListener(this);
                imageView.setTag("button_clear");
                imageView.setOnLongClickListener(this);

            } else {

                int buttonStyle = android.R.attr.borderlessButtonStyle;
                button = new Button(new ContextThemeWrapper(getContext(), android.R.attr.borderlessButtonStyle), null, buttonStyle);
                button.setBackground(getContext().getResources().getDrawable(mBackground));
                button.setTextColor(getContext().getResources().getColor(R.color.colorPrimary));
                button.setOnClickListener(this);

                button.setTypeface(null, Typeface.BOLD);

                if (gridHeight <= 400) button.setTextSize(14);
                else if (gridHeight <= 550) button.setTextSize(15);
//                else if(gridHeight<=660) button.setTextSize(18);
                else button.setTextSize(18);

                if (i == 10) button.setText(0 + "");
                else button.setText(i + 1 + "");
                gridLayout.addView(button, i);
                GridLayout.LayoutParams param = new GridLayout.LayoutParams();

                param.height = height;
                param.width = width;

                if (c == 0) param.leftMargin = 4;
                else if (c == 2) param.rightMargin = 3;
                else {
                    param.leftMargin = keyboardMargin;
                    param.rightMargin = keyboardMargin;
                }

                if (i < total - 9) param.topMargin = 0;
                else param.topMargin = keyboardMargin;

                param.setGravity(Gravity.CENTER);
                param.columnSpec = GridLayout.spec(c);
                param.rowSpec = GridLayout.spec(r);
                button.setLayoutParams(param);
            }
        }
        addView(gridLayout);
    }

    @Override
    public void onClick(View view) {

        String editString = mEditText != null ? mEditText.getText().toString() : " ";
        int pos = mEditText != null ? mEditText.getSelectionStart() : 0;


        try {
            if (view instanceof ImageView) {

                if (keyBoardNumberInteractor != null)
                    keyBoardNumberInteractor.onKeyBoardKeyClearClick();

                SpannableStringBuilder selectedStr = new SpannableStringBuilder(editString);
                editString = selectedStr.replace(pos - 1, pos, "").toString();
                updateEditText(editString);

                if (mEditText != null)
                    mEditText.setSelection(pos - 1);

            } else {

                if (keyBoardNumberInteractor != null)
                    keyBoardNumberInteractor.onKeyBoardKeyClick(((Button) view).getText().toString());
                editString = editString.substring(0, pos) + ((Button) view).getText().toString() + editString.substring(pos);
                if (!(editString.length() - 1 == mMaxLenght))
                    updateEditText(editString);

                if (mEditText != null && !TextUtils.isEmpty(editString)) {
                    if (editString.length() - 1 == mMaxLenght)
                        mEditText.setSelection(pos);
                    else {
                        mEditText.setSelection(pos + 1);
                    }
                }
            }

        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showKeyBoard(@NotNull EditText editText) {
        mEditText = editText;
        showKeyBoard();
    }

    public void setmEditText(@NotNull EditText editText) {
        mEditText = editText;
    }

    @Override
    public void showKeyBoard() {
        Objects.requireNonNull(AnimationUtil.Companion.getInstance()).expand(this);
        //AnimationUtil.getInstance().expand(this);
    }

    @Override
    public void hideKeyBoard() {
        Objects.requireNonNull(AnimationUtil.Companion.getInstance()).collapse(this);
        // AnimationUtil.getInstance().collapse(this);
    }

    private void updateEditText(String text) {

        if (mEditText != null) {
            mEditText.setText(text);
        }

        if (mCallBackKeySelect != null) {
            mCallBackKeySelect.callback(mEditText, text);
        }
    }

    public void setKeyBoardNumberInteractor(KeyBoardNumberInteractor keyBoardNumberInteractor) {
        this.keyBoardNumberInteractor = keyBoardNumberInteractor;
    }

    @Override
    public boolean onLongClick(View view) {

        if (mEditText != null) mEditText.setText("");

        return false;
    }

    public interface SelectKeyListener {
        void callback(View view, String result);
    }
}
