package com.feasy.feasyprint;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;

import androidx.annotation.Nullable;

import java.util.Locale;

public class ChronometerView extends androidx.appcompat.widget.AppCompatTextView {
    public interface TimerListener {
        void onTimeUpdate(String formattedTime, long elapsedMillis);
        void onTimerStart();
        void onTimerPause();
        void onTimerReset();
    }

    private long startTime = 0;
    private long elapsedTime = 0;
    private long pauseTime = 0;
    private boolean isRunning = false;

    private final Handler handler = new Handler(Looper.getMainLooper());
    private final Runnable updateTask = new Runnable() {
        @Override
        public void run() {
            if (isRunning) {
                updateTime();
                handler.postDelayed(this, 50); // 每10毫秒更新一次
            }
        }
    };

    private TimerListener listener;

    public ChronometerView(Context context) {
        super(context);
        init();
    }

    public ChronometerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

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

    private void init() {
        reset();
    }

    public void setTimerListener(TimerListener listener) {
        this.listener = listener;
    }

    public void start() {
        if (isRunning) return;

        if (pauseTime == 0) {
            // 第一次启动
            startTime = System.currentTimeMillis();
        } else {
            // 继续运行（从暂停恢复）
            startTime = System.currentTimeMillis() - elapsedTime;
        }

        isRunning = true;
        handler.post(updateTask);

        if (listener != null) {
            listener.onTimerStart();
        }
    }

    public void pause() {
        if (!isRunning) return;

        isRunning = false;
        handler.removeCallbacks(updateTask);
        pauseTime = System.currentTimeMillis();
        elapsedTime = pauseTime - startTime;

        if (listener != null) {
            listener.onTimerPause();
        }
    }

    public void reset() {
        isRunning = false;
        handler.removeCallbacks(updateTask);
        startTime = 0;
        elapsedTime = 0;
        pauseTime = 0;
        setText("00:00.000");

        if (listener != null) {
            listener.onTimerReset();
        }
    }

    public long getElapsedMillis() {
        if (isRunning) {
            return System.currentTimeMillis() - startTime;
        } else {
            return elapsedTime;
        }
    }

    public boolean isRunning() {
        return isRunning;
    }

    private void updateTime() {
        long currentElapsed = System.currentTimeMillis() - startTime;
        String formattedTime = formatTime(currentElapsed);
        setText(formattedTime);

        if (listener != null) {
            listener.onTimeUpdate(formattedTime, currentElapsed);
        }
    }

    public String formatTime(long millis) {
        long totalSeconds = millis / 1000;
        long minutes = totalSeconds / 60;
        long seconds = totalSeconds % 60;
        long milliseconds = millis % 1000;

        return String.format(Locale.getDefault(), "%02d:%02d.%03d",
                minutes, seconds, milliseconds);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        handler.removeCallbacks(updateTask);
    }
}