package com.kfzs.duanduan.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.AppCompatButton;
import android.util.AttributeSet;

import com.sheep.jiuyan.samllsheep.R;


/**
 * @ Created by Dlg
 * @ <p>TiTle:  TimeButton</p>
 * @ <p>Description: 一般用于验证码，计时按钮</p>
 * @ date:  2017/12/7 11:14
 * @ QQ:    315096953
 */
public class TimeButton extends AppCompatButton {
    private int mIntSeconds = 60;
    private int mRemainSeconds = 0;
    private final static int HANDLE_MSG = 1;

    public TimeButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setSeconds(int seconds) {
        this.mIntSeconds = seconds;
    }

    /**
     * 启动记时器
     */
    public void star() {
        setEnabled(false);
        mRemainSeconds = mIntSeconds;
        handler.sendEmptyMessage(HANDLE_MSG);
    }

    /**
     * 重置记时器
     */
    public void reset() {
        handler.removeMessages(HANDLE_MSG);
        mRemainSeconds = 0;
        setEnabled(true);
        setText(getResources()
                .getString(R.string.getvalicode));
    }

    /**
     * 是否已经初始化可点击状态中
     *
     * @return
     */
    public boolean isAlready() {
        return getText().equals(getResources()
                .getString(R.string.getvalicode));
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            setText(String.format(getResources()
                    .getString(R.string.delayretry), mRemainSeconds));
            if (mRemainSeconds <= 0) {
                setEnabled(true);
                setText(getResources()
                        .getString(R.string.getvalicode));
            } else
                sendEmptyMessageDelayed(HANDLE_MSG, 1000);
            mRemainSeconds--;
        }
    };

    @Override
    public void onDetachedFromWindow() {
        handler.removeMessages(HANDLE_MSG);
        mRemainSeconds = 0;
        super.onDetachedFromWindow();
    }
}
