package kr.co.hanwha.hifive.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import kr.co.hanwha.hifive.R;

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

public class HFPasswordEditTextView extends RelativeLayout {
    private EditText mEditTextPassword;
    private ImageView[] mImageViewDots;
    private int[] mRes = {R.id.dot1_imageView, R.id.dot2_imageView, R.id.dot3_imageView,
            R.id.dot4_imageView, R.id.dot5_imageView, R.id.dot6_imageView};

    private OnInputPasswordListener onInputPasswordListener;

    private final int MAX_LENGTH = 4;

    public HFPasswordEditTextView(Context context) {
        super(context);
        initialize(context);
    }

    public HFPasswordEditTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initialize(context, attrs);
    }

    public HFPasswordEditTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context, attrs);
    }

    public void setOnInputPasswordListener(OnInputPasswordListener onInputPasswordListener) {
        this.onInputPasswordListener = onInputPasswordListener;
    }

    private void initialize(Context context) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.view_hf_password_edittext, this, true);

        mEditTextPassword = (EditText) findViewById(R.id.password_editText);
        mEditTextPassword.addTextChangedListener(textWatcher);
        mEditTextPassword.setOnEditorActionListener(onEditorActionListener);

        mImageViewDots = new ImageView[mRes.length];
        for (int i = 0; i < mImageViewDots.length; i++) {
            mImageViewDots[i] = (ImageView) findViewById(mRes[i]);
            if (i >= MAX_LENGTH) mImageViewDots[i].setVisibility(View.GONE);
            else mImageViewDots[i].setVisibility(View.VISIBLE);
        }

        findViewById(R.id.body_linearLayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setFocus();
            }
        });
    }

    private void initialize(Context context, @Nullable AttributeSet attrs) {
        initialize(context);
        if (attrs != null) {
            TypedArray type = null;
            try {
//                type = context.obtainStyledAttributes(attrs, R.styleable.ToggleView);
//                String title = type.getString(R.styleable.ToggleView_toggleTitle);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (type != null) type.recycle();
            }
        }
    }

    public EditText getEditText() {
        return mEditTextPassword;
    }

    public String getText() {
        return mEditTextPassword.getText().toString();
    }

    private void setDots(int length) {
        for (int i = 0; i < mImageViewDots.length; i++) {
            mImageViewDots[i].setSelected(i < length);
        }

        if (length == MAX_LENGTH && onInputPasswordListener != null)
            onInputPasswordListener.onCompleteInput(mEditTextPassword.getText().toString());
    }

    public void clearData() {
        mEditTextPassword.setText("");
//        mEditTextPassword.requestFocus();
    }

    public void setFocus() {
//        mEditTextPassword.requestFocus();
//        mEditTextPassword.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                InputMethodManager input = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//                input.showSoftInput(mEditTextPassword, InputMethodManager.SHOW_IMPLICIT);
//            }
//        }, 100);
    }

    public void setNum(int num) {
        String text = getText();
        if (text.length() < MAX_LENGTH)
            mEditTextPassword.setText(text + num);
    }

    public void delNum() {
        String text = getText();
        if (text.length() > 0) {
            mEditTextPassword.setText(text.substring(0, text.length() - 1));
        }
    }

    /**
     * TextWatcher
     */
    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (onInputPasswordListener != null) onInputPasswordListener.onTextChanged();
        }

        @Override
        public void afterTextChanged(Editable s) {
            setDots(s.length());
        }
    };
    /**************************************************
     * TextView.OnEditorActionListener
     **************************************************/
    TextView.OnEditorActionListener onEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                if (onInputPasswordListener != null) {
                    String password = mEditTextPassword.getText().toString();
                    if (password.length() == MAX_LENGTH)
                        onInputPasswordListener.onCompleteInput(password);
                    else {
                        onInputPasswordListener.onErrorMessage(getContext().getString(R.string.change_pw_alert_empty_pw));
                        setFocus();
                    }
                }
            }
            return false;
        }
    };

    /**
     * OnInputPasswordListener
     */
    public interface OnInputPasswordListener {
        void onCompleteInput(String password);

        void onErrorMessage(String message);

        void onTextChanged();
    }
}
