package com.sheep.gamegroup.view.customview;

import android.content.Context;
import android.support.v7.widget.AppCompatButton;
import android.util.AttributeSet;
import android.view.View;

import com.sheep.gamegroup.util.SelfCountDownTimer;
import com.sheep.jiuyan.samllsheep.R;

import java.text.MessageFormat;
import java.util.Locale;

public class CountDownButton extends AppCompatButton {

    private String freezonText = "发送验证码({0}s)";
    private String enableText = "发送验证码";

    private int cooldown = 60;

    private OnClickListener exlistener;

    private SelfCountDownTimer selfCountDownTimer = new SelfCountDownTimer(cooldown * 1000, 1000, cooldown) {
        @Override
        public void onTimerRest() {
            setText(enableText);
            setEnabled(true);
        }

        @Override
        public void onTimerTick(long millisUntilFinished, int countTime) {
            setText(MessageFormat.format(freezonText, countTime));
        }

        @Override
        public void onTimerFinish() {
            setEnabled(true);
            setText(enableText);
        }
    };

    public CountDownButton(Context context) {
        super(context);
    }

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

    public CountDownButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setCooldown(int cooldown) {
        this.cooldown = cooldown;
    }

    public void startTimer() {
        this.setEnabled(false);

    }

    @Override
    public void setOnClickListener(OnClickListener exlistener) {
        this.exlistener = exlistener;
        super.setOnClickListener(v -> click());
    }

    public void click() {
        selfCountDownTimer.reset(cooldown);
        selfCountDownTimer.start();
        setEnabled(false);
        exlistener.onClick(this);
    }

    public void setFreezonText(String freezonText) {
        this.freezonText = freezonText;
    }

    public void setEnableText(String enableText) {
        this.enableText = enableText;
    }

    public void onDestroy() {
        if (selfCountDownTimer != null) {
            selfCountDownTimer.cancel();
            selfCountDownTimer = null;
        }
    }
}
