package xyz.upperlevel.uppercore.task;

import lombok.Getter;
import org.bukkit.scheduler.BukkitRunnable;
import xyz.upperlevel.uppercore.Uppercore;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.function.Consumer;

public abstract class Countdown extends BukkitRunnable {
    @Getter
    private final long startAt, repeatEach;

    @Getter
    private long currentTick;

    public Countdown(long startAt, long repeatEach) {
        this.startAt = startAt;
        this.repeatEach = repeatEach;
    }

    public void start() {
        currentTick = startAt;
        runTaskTimer(Uppercore.plugin(), 0, repeatEach);
    }

    public long getTime() {
        return currentTick / repeatEach;
    }

    protected abstract void onTick(long time);

    protected abstract void onEnd();

    @Override
    public void run() {
        onTick(currentTick / repeatEach);
        if (currentTick > 0)
            currentTick -= repeatEach;
        else {
            onEnd();
            super.cancel();
        }
    }

    public String toString(String pattern) {
        return new SimpleDateFormat(pattern).format(new Date(currentTick * 50));
    }

    public static Countdown create(long startAt, long repeatEach, Consumer<Long> onTick, Runnable onEnd) {
        return new Countdown(startAt, repeatEach) {
            @Override
            protected void onTick(long tick) {
                onTick.accept(tick);
            }

            @Override
            protected void onEnd() {
                onEnd.run();
            }
        };
    }
}

@@ -573,32 +573,45 @@
 ntTick = startAt
+ + repeatEach
 ;%0A        runTas
@@ -868,23 +868,16 @@
         
-onTick(
 currentT
@@ -872,33 +872,34 @@
     currentTick 
-/
+-=
  repeatEach);%0A  
@@ -889,25 +889,24 @@
 = repeatEach
-)
 ;%0A        if
@@ -923,12 +923,15 @@
 ick 
-%3E
+==
  0)
+ %7B
 %0A   
@@ -943,33 +943,43 @@
     
-currentTick -= repeatEach
+onEnd();%0A            super.cancel()
 ;%0A  
@@ -983,16 +983,18 @@
 %0A       
+ %7D
  else %7B%0A
@@ -1011,40 +1011,37 @@
   on
-End();%0A            super.cancel(
+Tick(currentTick / repeatEach
 );%0A 

Fix countdown time sudden change during board updates