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 static LocalDateTime nextPulse;
    public MineThread(){

    }
    @Override
    public void run() {
        nextPulse = LocalDateTime.now().withMinute(0).withSecond(0).withNano(0);
        while (true) {
            if(LocalDateTime.now().isAfter(nextPulse)) {
                processMineWindows();
            }
        }
    }

    public static void mineWindowOpen(Mine mine) {

        mine.setActive(true);
        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;
    }

    public static void processMineWindows(){
        for (Mine mine : Mine.getMines()) {
            Building tower = BuildingManager.getBuildingFromCache(mine.getBuildingID());
            //if the tower comes back null, skip this mine
            if(tower == null)
                continue;

            //log the current time right now
            LocalDateTime currentTime = LocalDateTime.now().plusMinutes(1);

            //check if this mine needs to open
            LocalDateTime openTime = LocalDateTime.now().withHour(mine.liveHour).withMinute(mine.liveMinute).withSecond(0).withNano(0);
            if(currentTime.isAfter(openTime) && currentTime.isBefore(openTime.plusMinutes(30)) && !mine.wasOpened){
                mineWindowOpen(mine); //hour and minute match, time to open the window
                ChatManager.chatSystemChannel(mine.getParentZone().getName() + " " +  mine.getMineType() + "MINE is now vulnerable to attack!");
                continue;
            }

            //check to see if the window shoul dbe closing now
            if(currentTime.isAfter(openTime.plusMinutes(29)) && mine.isActive) {
                //check to see if the tower was destoryed
                boolean towerDestroyed = tower.getRank() < 1;
                if(towerDestroyed){
                    //check if a valid claimer exists to close the window and claim the mine since the tower was destroyed
                    if(mine.lastClaimer != null) {
                        mineWindowClose(mine);
                        ChatManager.chatSystemChannel("The fight for " + mine.getParentZone().getName() + " " +  mine.getMineType() + " MINE has concluded. " + mine.lastClaimer.getName() + " has seized it in the name of " + mine.lastClaimer.getGuild().getNation());
                    }else{
                        ChatManager.chatSystemChannel("The " + mine.getParentZone().getName() + " " +  mine.getMineType() + " MINE is still unclaimed. The battle continues.");
                    }
                }else{
                    //tower was not destroyed, mine window closes
                    mineWindowClose(mine);
                    ChatManager.chatSystemChannel(tower.getGuild().getNation().getName() + "  has successfully defended the " + mine.getParentZone().getName() + " " +  mine.getMineType() + " MINE, and retains their claim.");
                }

            }
        }
        nextPulse = nextPulse.plusMinutes(30);
    }
}
