package engine.workthreads;

import engine.Enum;
import engine.InterestManagement.WorldGrid;
import engine.db.archive.DataWarehouse;
import engine.db.archive.MineRecord;
import engine.gameManager.BuildingManager;
import engine.gameManager.ChatManager;
import engine.net.DispatchMessage;
import engine.net.client.msg.chat.ChatSystemMsg;
import engine.objects.Building;
import engine.objects.Guild;
import engine.objects.Mine;
import engine.objects.PlayerCharacter;
import org.pmw.tinylog.Logger;

import java.time.LocalDateTime;

public class MineThread  implements Runnable {
    public MineThread(){

    }
    @Override
    public void run() {
        LocalDateTime nextPulse = LocalDateTime.now().withMinute(0).withSecond(0).withNano(0);
        while (true){
            if(LocalDateTime.now().isAfter(nextPulse)) {
                for (Mine mine : Mine.getMines()) {

                    if(nextPulse.getHour() == 2 && nextPulse.getMinute() == 0){
                        mine.wasClaimed = false;
                        mine.hasProduced = false;

                    }
                    Building mineTower = BuildingManager.getBuilding(mine.getBuildingID());

                    if (mineTower == null)
                        continue;

                    int minute = 0;
                    if (mine.firstThirty == false)
                        minute = 30;

                    LocalDateTime openTime = LocalDateTime.now().withHour(mine.liveTime).withMinute(minute).withSecond(0);
                    LocalDateTime closeTime = openTime.plusMinutes(29);

                    //current time is after start time and before close time, open mine window
                    if (LocalDateTime.now().isAfter(openTime.minusMinutes(1)) && !mine.wasClaimed && !mine.wasOpened) {
                        mineWindowOpen(mine);
                        continue;
                    }
                    if (mine.isActive) {

                        if (LocalDateTime.now().isAfter(closeTime) && mineTower.getRank() > 0)
                            mineWindowClose(mine); //mine was never knocked down, close window

                        if (LocalDateTime.now().isAfter(closeTime) && mineTower.getRank() < 1 && mine.lastClaimer != null)
                            mineWindowClose(mine); //mine was knocked down and was claimed, close window
                    }
                }
                nextPulse = nextPulse.plusMinutes(30);
            }
        }
    }

    public static void mineWindowOpen(Mine mine) {

        mine.setActive(true);
        ChatManager.chatSystemChannel(mine.getParentZone().getName() + "'s Mine is now Active!");
        Logger.info(mine.getParentZone().getName() + "'s Mine is now Active!");
    }

    public static boolean mineWindowClose(Mine mine) {

        // No need to end the window of a mine which never opened.

        if (mine.isActive == false)
            return false;

        Building mineBuilding = BuildingManager.getBuildingFromCache(mine.getBuildingID());

        if (mineBuilding == null) {
            Logger.debug("Null mine building for Mine " + mine.getObjectUUID() + " Building " + mine.getBuildingID());
            return false;
        }

        for(Integer id : mine._playerMemory ){
            PlayerCharacter.getPlayerCharacter(id).ZergMultiplier = 1.0f;
        }
        for(Integer id : mine._recentMemory.keySet()){
            PlayerCharacter.getPlayerCharacter(id).ZergMultiplier = 1.0f;
        }
        // Mine building still stands; nothing to do.
        // We can early exit here.

        if (mineBuilding.getRank() > 0) {
            mine.setActive(false);
            mine.lastClaimer = null;
            return true;
        }

        // This mine does not have a valid claimer
        // we will therefore set it to errant
        // and keep the window open.

        if (!Mine.validateClaimer(mine.lastClaimer)) {
            mine.lastClaimer = null;
            mine.updateGuildOwner(null);
            mine.setActive(true);
            return false;
        }

        //Update ownership to map

        mine.guildName = mine.getOwningGuild().getName();
        mine.guildTag = mine.getOwningGuild().getGuildTag();
        Guild nation = mine.getOwningGuild().getNation();
        mine.nationName = nation.getName();
        mine.nationTag = nation.getGuildTag();

        mineBuilding.rebuildMine(mine.capSize * 5000);
        WorldGrid.updateObject(mineBuilding);

        ChatSystemMsg chatMsg = new ChatSystemMsg(null, mine.lastClaimer.getName() + " has claimed the mine in " + mine.getParentZone().getName() + " for " + mine.getOwningGuild().getName() + ". The mine is no longer active.");
        chatMsg.setMessageType(10);
        chatMsg.setChannel(Enum.ChatChannelType.SYSTEM.getChannelID());
        DispatchMessage.dispatchMsgToAll(chatMsg);

        // Warehouse this claim event

        MineRecord mineRecord = MineRecord.borrow(mine, mine.lastClaimer, Enum.RecordEventType.CAPTURE);
        DataWarehouse.pushToWarehouse(mineRecord);

        mineBuilding.setRank(mineBuilding.getRank());
        mine.lastClaimer = null;
        mine.setActive(false);
        mine.wasClaimed = true;
        return true;
    }
}
