package cz.jzitnik.game.blocks;

import cz.jzitnik.game.Game;
import cz.jzitnik.game.annotations.RightClickLogic;
import cz.jzitnik.game.context.list.BedSleepGlobalContext;
import cz.jzitnik.game.handlers.rightclick.RightClickHandler;
import cz.jzitnik.tui.ScreenRenderer;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@RightClickLogic
public class Bed implements RightClickHandler {

    @Override
    public void onBlockRightClick(int x, int y, Game game, ScreenRenderer screenRenderer) {
        BedSleepGlobalContext bedSleepGlobalContext =
                (BedSleepGlobalContext) game.getContext(BedSleepGlobalContext.class);

        if (bedSleepGlobalContext.isSleeping() || game.getDaytime() < 200 || game.getDaytime() > 500) {
            return; // already in progress
        }

        bedSleepGlobalContext.setSleeping(true);

        int targetTime = 500;
        int step = 10;
        long delayMillis = 50; // animation speed

        // Create a brand-new scheduler for this run
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

        final ScheduledFuture<?>[] futureHolder = new ScheduledFuture<?>[1];

        Runnable sleepTask = () -> {
            int currentTime = game.getDaytime();

            if (currentTime == targetTime) {
                // cancel this repeating task + shut down the scheduler
                futureHolder[0].cancel(false);
                scheduler.shutdown();
                bedSleepGlobalContext.setSleeping(false);
                return;
            }

            int nextTime = (currentTime + step) % 600;

            if (currentTime < targetTime && nextTime >= targetTime) {
                nextTime = targetTime;
            }

            if (nextTime < currentTime && nextTime >= targetTime) {
                nextTime = targetTime;
            }

            game.setDaytime(nextTime);
            screenRenderer.render(game);
        };

        // Schedule the task and keep its handle
        futureHolder[0] = scheduler.scheduleAtFixedRate(
                sleepTask, 0, delayMillis, TimeUnit.MILLISECONDS);
    }
}
