package de.steamwar.bausystem.region;

import com.sk89q.worldedit.EditSession;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.region.flags.ChangedMode;
import de.steamwar.bausystem.region.flags.Flag;
import de.steamwar.linkage.Linked;
import de.steamwar.linkage.api.Enable;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.Iterator;

@Linked
public class BackupScheduler implements Enable {

    private static final long INITIAL = 20 * 60 * 5;
    private static final long PERIOD = 20 * 60 * 30;

    @Override
    public void enable() {
        new BukkitRunnable() {
            @Override
            public void run() {
                Iterator<Region> regionsToBackup = RegionSystem.INSTANCE.getRegions()
                        .filter(region -> region.getFlags().has(Flag.CHANGED).isReadable())
                        .filter(region -> region.getFlags().get(Flag.CHANGED).get() == ChangedMode.HAS_CHANGE)
                        .iterator();
                if (!regionsToBackup.hasNext()) return;
                doBackup(regionsToBackup);
            }
        }.runTaskTimer(BauSystem.getInstance(), INITIAL, PERIOD);
    }

    private void doBackup(Iterator<Region> regionsToBackup) {
        new BukkitRunnable() {
            @Override
            public void run() {
                if (!regionsToBackup.hasNext()) {
                    this.cancel();
                    return;
                }

                Region region = regionsToBackup.next();
                EditSession editSession = region.getArea()
                        .copy(false);
                // TODO: Implement saving EditSession to schematic!
                region.getFlags().set(Flag.CHANGED, ChangedMode.NO_CHANGE);
            }
        }.runTaskTimer(BauSystem.getInstance(), 0, 20 * 60);
    }
}
