package com.cygnusa.hyperm.util;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

@SuppressLint("AppCompatCustomView")
public class TimerTextView extends TextView {

    private static final int DEFAULT_INTERVAL = 1000;
    private Timer timer = new Timer();
    private boolean isCanceled = false;
    private int SECONDS = 0;

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

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

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

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public TimerTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopTimer();
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
    }

    public void startTimer() {
        if (isCanceled) {
            timer = new Timer();
            isCanceled = false;
        }
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (null == getHandler()) {
                    return;
                }
                SECONDS++;
                getHandler().post(() -> setText(getDurationBreakdown()));
            }
        }, 0, DEFAULT_INTERVAL);
    }

    public void stopTimer() {
        timer.cancel();
        isCanceled = true;
    }

    public int getSeconds() {
        return SECONDS;
    }

    private String getDurationBreakdown() {
        int secondsLeft = SECONDS % 3600 % 60;
        int minutes = (int) Math.floor(SECONDS % 3600 / 60);
        int hours = (int) Math.floor(SECONDS / 3600);
        String HH = ((hours < 10) ? "0" : "") + hours;
        String MM = ((minutes < 10) ? "0" : "") + minutes;
        String SS = ((secondsLeft < 10) ? "0" : "") + secondsLeft;
        return HH + ":" + MM + ":" + SS;
    }
}
