package kr.co.hanwha.hifive.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
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.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.UnsupportedEncodingException;

import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.util.HFCommonUtil;

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

public class HFSearchEditTextView extends LinearLayout {
    private ImageView mImageViewSearch;
    private EditText mEditText;
    private ImageButton mImageButtonClear;
    private View mViewLine;

    private OnSearchEditTextListener onSearchEditTextListener;

    private boolean mClearVisible = true;

    private String mLastText = "";
    private int mLimitLength = 0;

    public void setOnSearchEditTextListener(OnSearchEditTextListener onSearchEditTextListener) {
        this.onSearchEditTextListener = onSearchEditTextListener;
    }

    public HFSearchEditTextView(Context context) {
        super(context);
        initialize(context, null);
    }

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

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

    private void initialize(Context context, @Nullable AttributeSet attrs) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.view_hf_search_edittext, this, true);

        mImageViewSearch = (ImageView) findViewById(R.id.search_imageView);
        mEditText = (EditText) findViewById(R.id.editText);
        mImageButtonClear = (ImageButton) findViewById(R.id.clear_imageButton);
        mViewLine = (View) findViewById(R.id.line_view);

        mEditText.setOnEditorActionListener(onEditorActionListener);
        mEditText.addTextChangedListener(textWatcher);
        mEditText.setOnFocusChangeListener(onFocusChangeListener);

        mImageButtonClear.setOnClickListener(onClickListener);

        boolean focus = true;
        if (attrs != null) {
            TypedArray type = null;
            try {
                type = context.obtainStyledAttributes(attrs, R.styleable.SearchEdit);

                focus = type.getBoolean(R.styleable.SearchEdit_focus, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (focus) {
            mEditText.requestFocus();
            mEditText.postDelayed(new Runnable() {
                @Override
                public void run() {
                    InputMethodManager input = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    input.showSoftInput(mEditText, InputMethodManager.SHOW_IMPLICIT);
                }
            }, 100);
        }
    }

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

    public void clearText() {
        mEditText.setText("");
    }

    public void setText(@Nullable String text) {
        if (TextUtils.isEmpty(text) == false) {
            mEditText.setText(text);
        }
    }

    public boolean setFocus() {
        return mEditText.requestFocus();
    }

    /**
     * 바이트로 길이 제한
     *
     * @param byteLength 최대 바이트
     */
    public void setLengthLimit(int byteLength) {
        mLimitLength = byteLength;
//        InputFilter[] filters = new InputFilter[]{new ByteLengthFilter(byteLength, "KSC5601")};
//        mEditText.setFilters(filters);
    }

    /**
     * 문자열 바이트 길이
     *
     * @param str 문자열
     * @return Length
     */
    private int getByteLength(String str) {
        try {
            return str.getBytes("KSC5601").length;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 데이터 확인
     *
     * @return TRUE : EMPTY
     */
    public boolean isEmpty() {
        return (TextUtils.isEmpty(getText()));
    }

    public void hideKeyboard() {
        ((InputMethodManager) mEditText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }

    /**************************************************
     * OnClickListener
     **************************************************/
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.clear_imageButton:
                    mEditText.setText("");
                    break;
            }
        }
    };

    /**************************************************
     * TextView.OnEditorActionListener
     **************************************************/
    TextView.OnEditorActionListener onEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                hideKeyboard();

                if (onSearchEditTextListener != null)
                    onSearchEditTextListener.onImeActionSearch(HFSearchEditTextView.this);
                return true;
            }
            return false;
        }
    };

    /**************************************************
     * OnFocusChangeListener
     **************************************************/
    OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if (b) {
                mImageViewSearch.setAlpha(1.0f);
                mViewLine.setBackgroundColor(HFCommonUtil.getColor(getContext(), R.color.black));
                if (mEditText.getText().toString().length() > 0 && mClearVisible)
                    mImageButtonClear.setVisibility(VISIBLE);
            } else {
                mImageViewSearch.setAlpha(0.3f);
                mImageButtonClear.setVisibility(View.GONE);
                mViewLine.setBackgroundColor(HFCommonUtil.getColor(getContext(), R.color.gray_d5));
            }
        }
    };

    /**************************************************
     * EditText - TextWatcher
     **************************************************/
    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            mLastText = s.toString();
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() > 0 && mClearVisible && mEditText.isFocused()) {
                mImageButtonClear.setVisibility(VISIBLE);
            } else {
                mImageButtonClear.setVisibility(GONE);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (onSearchEditTextListener != null)
                onSearchEditTextListener.onValueChanged(HFSearchEditTextView.this);

            if (mLimitLength > 0) {
                if (mLimitLength < getByteLength(s.toString())) {
                    mEditText.setText(mLastText);
                    mEditText.setSelection(mLastText.length());
                } else {
                    mLastText = s.toString();
                }
            }
        }
    };

    /**************************************************
     * OnSearchEditTextListener
     **************************************************/
    public interface OnSearchEditTextListener {
        void onImeActionSearch(@NonNull HFSearchEditTextView v);

        void onValueChanged(@NonNull HFSearchEditTextView v);
    }
}
