// • ▌ ▄ ·.  ▄▄▄·  ▄▄ • ▪   ▄▄· ▄▄▄▄·  ▄▄▄·  ▐▄▄▄  ▄▄▄ .
// ·██ ▐███▪▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▐█ ▀█▪▐█ ▀█ •█▌ ▐█▐▌·
// ▐█ ▌▐▌▐█·▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐█▀▀█▄▄█▀▀█ ▐█▐ ▐▌▐▀▀▀
// ██ ██▌▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌██▄▪▐█▐█ ▪▐▌██▐ █▌▐█▄▄▌
// ▀▀  █▪▀▀▀ ▀  ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ ·▀▀▀▀  ▀  ▀ ▀▀  █▪ ▀▀▀
//      Magicbane Emulator Project © 2013 - 2022
//                www.magicbane.com

package engine.gameManager;

// Defines static methods which comprise the magicbane
// building maintenance system.

import engine.mbEnums;
import engine.objects.Building;
import engine.objects.City;
import engine.objects.Warehouse;
import org.pmw.tinylog.Logger;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;

public enum MaintenanceManager {

    MAINTENANCEMANAGER;

    public static void setMaintDateTime(Building building, LocalDateTime maintDate) {

        building.maintDateTime = maintDate;
        DbManager.BuildingQueries.updateMaintDate(building);

    }

    public static void processBuildingMaintenance() {

        ArrayList<Building> buildingList;
        ArrayList<Building> maintList;
        ArrayList<Building> tolList;
        ArrayList<Building> structureDerank = new ArrayList<>();
        ArrayList<Building> tolDerank = new ArrayList<>();

        Logger.info("Starting Maintenance on Player Buildings");

        // Build list of buildings to apply maintenance on.

        buildingList = new ArrayList(DbManager.getList(mbEnums.GameObjectType.Building));
        HashMap<String, ArrayList<Building>> maintMap = new HashMap<>();

        maintMap = buildMaintList(buildingList);

        maintList = maintMap.get("maint");
        tolList = maintMap.get("tol");

        // Deduct upkeep and build list of buildings
        // which did not have funds available

        try {
            for (Building building : maintList)
                if (chargeUpkeep(building) == false)
                    structureDerank.add(building);
        } catch (Exception e) {
            Logger.error(e);
        }

        // Reset maintenance dates for these buildings

        for (Building building : maintList)
            setMaintDateTime(building, LocalDateTime.now().plusDays(7));

        // Derak or destroy buildings that did not
        // have funds available.

        try {
            for (Building building : structureDerank)
                building.destroyOrDerank(null);
        } catch (Exception e) {
            Logger.error(e);
        }

        // Process TOL maintenance

        try {
            for (Building building : tolList)
                if (chargeUpkeep(building) == false)
                    tolDerank.add(building);
        } catch (Exception e) {
            Logger.error(e);
        }

        // Reset maintenance dates for these buildings

        for (Building building : tolList)
            setMaintDateTime(building, LocalDateTime.now().plusDays(7));

        // Derak or destroy buildings that did not
        // have funds available.

        try {
            for (Building building : tolDerank)
                building.destroyOrDerank(null);
        } catch (Exception e) {
            Logger.error(e);
        }

        Logger.info("Structures: " + structureDerank.size() + "/" + maintList.size() + " TOLS: " + tolDerank.size() + "/" + tolList.size());
    }

    // Iterate over all buildings in game and apply exclusion rules
    // returning a list of building for which maintenance is due.

    private static HashMap<String, ArrayList<Building>> buildMaintList(ArrayList<Building> buildingList) {

        HashMap<String, ArrayList<Building>> outMap = new HashMap<>();
        ArrayList<Building> maintList = new ArrayList<>();
        ArrayList<Building> tolList = new ArrayList<>();

        for (Building building : buildingList) {

            // No maintenance on NPC owned buildings (Cache loaded)

            if (building.getProtectionState() == mbEnums.ProtectionState.NPC)
                continue;

            // No maintenance on constructing meshes

            if (building.getRank() < 1)
                continue;

            // No Maintenance on furniture

            if (building.parentBuildingID != 0)
                continue;

            // No Blueprint?

            if (building.getBlueprint() == null) {
                Logger.error("Blueprint missing for uuid: " + building.getObjectUUID());
                continue;
            }

            // No maintenance on banestones omfg

            if (building.getBlueprint().getBuildingGroup().equals(mbEnums.BuildingGroup.BANESTONE))
                continue;

            // no maintenance on Mines omfg

            if (building.getBlueprint().getBuildingGroup().equals(mbEnums.BuildingGroup.MINE))
                continue;

            // Null Maintenance date?

            if (building.maintDateTime == null) {
                Logger.error("Null maint date for building UUID: " + building.getObjectUUID());
                continue;
            }

            // Maintenance date is in the future

            if (building.maintDateTime.isAfter(LocalDateTime.now()))
                continue;


            //no maintenance if day of week doesn't match

            if (LocalDateTime.now().getDayOfWeek() != building.maintDateTime.getDayOfWeek())
                continue;

            //  Add building to maintenance queue

            if (building.getBlueprint().getBuildingGroup().equals(mbEnums.BuildingGroup.TOL))
                tolList.add(building);
            else
                maintList.add(building);
        }

        outMap.put("maint", maintList);
        outMap.put("tol", tolList);

        return outMap;
    }

    // Method removes the appropriate amount of gold/resources from
    // a building according to it's maintenance schedule.  True/False
    // is returned indicating if the building had enough funds to cover.

    public static boolean chargeUpkeep(Building building) {

        City city = null;
        Warehouse warehouse = null;
        int maintCost = 0;
        int overDraft = 0;
        boolean hasFunds = false;
        boolean hasResources = false;
        int resourceValue = 0;

        city = building.getCity();

        if (city != null)
            warehouse = city.warehouse;

        // Cache maintenance cost value

        maintCost = building.getMaintCost();

        // Something went wrong.  Missing buildinggroup from switch?

        if (maintCost == 0) {
            Logger.error("chargeUpkeep", "Error retrieving rankcost for " + building.getName() + " uuid:" + building.getObjectUUID() + "buildinggroup:" + building.getBlueprint().getBuildingGroup().name());
            // check if there is enough gold on the building
            return true;
        }

        if (building.getStrongboxValue() >= maintCost)
            hasFunds = true;

        // If we cannot cover with just the strongbox
        // see if there is a warehouse that will cover
        // the overdraft for us.


        if (hasFunds == false && (building.assetIsProtected() || building.getBlueprint().getBuildingGroup() == mbEnums.BuildingGroup.WAREHOUSE)) {
            overDraft = maintCost - building.getStrongboxValue();
        }

        if ((overDraft > 0))
            if ((building.getBlueprint().getBuildingGroup().equals(mbEnums.BuildingGroup.SHRINE) == false) &&
                    (warehouse != null) && building.assetIsProtected() == true &&
                    (warehouse.resources.get(mbEnums.ResourceType.GOLD)) >= overDraft) {
                hasFunds = true;
            }

        // If this is an R8 tree, validate that we can
        // cover the resources required

        if (building.getRank() == 8) {

            hasResources = true;

            if (warehouse == null)
                hasResources = false;
            else {

                resourceValue = warehouse.resources.get(mbEnums.ResourceType.STONE);

                if (resourceValue < 1500)
                    hasResources = false;

                resourceValue = warehouse.resources.get(mbEnums.ResourceType.LUMBER);

                if (resourceValue < 1500)
                    hasResources = false;

                resourceValue = warehouse.resources.get(mbEnums.ResourceType.GALVOR);

                if (resourceValue < 5)
                    hasResources = false;

                resourceValue = warehouse.resources.get(mbEnums.ResourceType.WORMWOOD);

                if (resourceValue < 5)
                    hasResources = false;

            }
        }
        // Validation completed but has failed.  We can derank
        // the target building and early exit

        if ((hasFunds == false) ||
                ((building.getRank() == 8) && !hasResources)) {

            // Add cash back to strongbox for lost rank if the building isn't being destroyed
            // and it's not an R8 deranking

            if ((building.getRank() > 1) && (building.getRank() < 8)) {
                building.setStrongboxValue(building.getStrongboxValue() + building.getBlueprint().getRankCost(Math.min(building.getRank(), 7)));
            }

            return false; // Early exit for having failed to meet maintenance
        }

        // Remove cash and resources

        // withdraw what we can from the building

        building.setStrongboxValue(building.getStrongboxValue() - (maintCost - overDraft));

        // withdraw overdraft from the whorehouse

        if (overDraft > 0) {

            resourceValue = warehouse.resources.get(mbEnums.ResourceType.GOLD);
            warehouse.resources.put(mbEnums.ResourceType.GOLD, resourceValue - overDraft);

            if (!DbManager.WarehouseQueries.UPDATE_WAREHOUSE(warehouse)) {
                warehouse.resources.put(mbEnums.ResourceType.GOLD, resourceValue);
                Logger.error("gold update failed for warehouse of city:" + warehouse.city.getName());
                return true;
            }

            Warehouse.AddTransactionToWarehouse(warehouse, mbEnums.GameObjectType.Building, building.getObjectUUID(), mbEnums.TransactionType.WITHDRAWL, mbEnums.ResourceType.GOLD, overDraft);
        }

        // Early exit as we're done if we're not an R8 tree

        if (building.getRank() < 8)
            return true;

        // Now for the resources if it's an R8 tree

        // Withdraw Stone

        resourceValue = warehouse.resources.get(mbEnums.ResourceType.STONE);
        warehouse.resources.put(mbEnums.ResourceType.STONE, resourceValue - 1500);

        if (!DbManager.WarehouseQueries.UPDATE_WAREHOUSE(warehouse)) {
            warehouse.resources.put(mbEnums.ResourceType.STONE, resourceValue);
            Logger.error("stone update failed for warehouse of city:" + warehouse.city.getName());
            return true;
        }

        Warehouse.AddTransactionToWarehouse(warehouse, mbEnums.GameObjectType.Building, building.getObjectUUID(), mbEnums.TransactionType.WITHDRAWL, mbEnums.ResourceType.STONE, 1500);

        // Withdraw Lumber

        resourceValue = warehouse.resources.get(mbEnums.ResourceType.LUMBER);
        warehouse.resources.put(mbEnums.ResourceType.LUMBER, resourceValue - 1500);

        if (!DbManager.WarehouseQueries.UPDATE_WAREHOUSE(warehouse)) {
            warehouse.resources.put(mbEnums.ResourceType.STONE, resourceValue);
            Logger.error("lumber update failed for warehouse of city:" + warehouse.city.getName());
            return true;
        }

        Warehouse.AddTransactionToWarehouse(warehouse, mbEnums.GameObjectType.Building, building.getObjectUUID(), mbEnums.TransactionType.WITHDRAWL, mbEnums.ResourceType.LUMBER, 1500);

        // Withdraw Galvor

        resourceValue = warehouse.resources.get(mbEnums.ResourceType.GALVOR);
        warehouse.resources.put(mbEnums.ResourceType.GALVOR, resourceValue - 5);

        if (!DbManager.WarehouseQueries.UPDATE_WAREHOUSE(warehouse)) {
            warehouse.resources.put(mbEnums.ResourceType.GALVOR, resourceValue);
            Logger.error("GALVOR update failed for warehouse of city:" + warehouse.city.getName());
            return true;
        }
        Warehouse.AddTransactionToWarehouse(warehouse, mbEnums.GameObjectType.Building, building.getObjectUUID(), mbEnums.TransactionType.WITHDRAWL, mbEnums.ResourceType.GALVOR, 5);

        // Withdraw GWORMWOOD

        resourceValue = warehouse.resources.get(mbEnums.ResourceType.WORMWOOD);
        warehouse.resources.put(mbEnums.ResourceType.WORMWOOD, resourceValue - 5);

        if (!DbManager.WarehouseQueries.UPDATE_WAREHOUSE(warehouse)) {
            warehouse.resources.put(mbEnums.ResourceType.GALVOR, resourceValue);
            Logger.error("wyrmwood update failed for warehouse of city:" + warehouse.city.getName());
            return true;
        }

        Warehouse.AddTransactionToWarehouse(warehouse, mbEnums.GameObjectType.Building, building.getObjectUUID(), mbEnums.TransactionType.WITHDRAWL, mbEnums.ResourceType.WORMWOOD, 5);

        return true;
    }

    public static void dailyMaintenance() {

        Logger.info("Maintenance has started");

        // Run maintenance on player buildings

        if (ConfigManager.MB_WORLD_MAINTENANCE.getValue().equalsIgnoreCase("true"))
            processBuildingMaintenance();
        else
            Logger.info("Maintenance Costings: DISABLED");

        Logger.info("Maintenance has completed!");
    }
}
