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


package engine.db.handlers;

import engine.gameManager.DbManager;
import engine.gameManager.ForgeManager;
import engine.loot.WorkOrder;
import engine.mbEnums;
import engine.mbEnums.GameObjectType;
import engine.mbEnums.TransactionType;
import engine.objects.Building;
import engine.objects.City;
import engine.objects.Transaction;
import engine.objects.Warehouse;
import engine.server.MBServerStatics;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONObject;
import org.pmw.tinylog.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

public class dbWarehouseHandler extends dbHandlerBase {

    private static final ConcurrentHashMap<Integer, String> columns = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW);

    public dbWarehouseHandler() {

    }

    public boolean CREATE_TRANSACTION(int warehouseBuildingID, GameObjectType targetType, int targetUUID, TransactionType transactionType, mbEnums.ResourceType resource, int amount, DateTime date) {

        try (Connection connection = DbManager.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_warehouse_transactions` (`warehouseUID`, `targetType`,`targetUID`, `type`,`resource`,`amount`,`date` ) VALUES (?,?,?,?,?,?,?)")) {

            preparedStatement.setLong(1, warehouseBuildingID);
            preparedStatement.setString(2, targetType.name());
            preparedStatement.setLong(3, targetUUID);
            preparedStatement.setString(4, transactionType.name());
            preparedStatement.setString(5, resource.name());
            preparedStatement.setInt(6, amount);
            preparedStatement.setTimestamp(7, new java.sql.Timestamp(date.getMillis()));

            return (preparedStatement.executeUpdate() > 0);

        } catch (SQLException e) {
            Logger.error(e);
        }
        return false;
    }

    public ArrayList<Transaction> GET_TRANSACTIONS_FOR_WAREHOUSE(final int warehouseUUID) {

        ArrayList<Transaction> transactionsList = new ArrayList<>();


        try (Connection connection = DbManager.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM dyn_warehouse_transactions WHERE `warehouseUID` = ?;")) {

            preparedStatement.setInt(1, warehouseUUID);

            ResultSet rs = preparedStatement.executeQuery();

            while (rs.next()) {
                Transaction transactions = new Transaction(rs);
                transactionsList.add(transactions);
            }

        } catch (SQLException e) {
            Logger.error(e);
        }

        return transactionsList;
    }

    public void DELETE_WAREHOUSE(Warehouse warehouse) {
        try (Connection connection = DbManager.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_warehouse` WHERE `cityUUID` = ?;")) {
            preparedStatement.setInt(1, warehouse.city.getObjectUUID());
            preparedStatement.executeUpdate();

        } catch (SQLException e) {
            Logger.error(e);
        }

    }

    public boolean UPDATE_WAREHOUSE(Warehouse warehouse) {

        JSONObject warehouseJSON = new JSONObject();

        JSONObject resources = new JSONObject(warehouse.resources);
        warehouseJSON.put("resources", resources);

        JSONArray locks = new JSONArray();

        for (mbEnums.ResourceType resource : warehouse.locked)
            locks.put(resource.name());

        warehouseJSON.put("locked", locks);

        try (Connection connection = DbManager.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_warehouse` (`cityUUID`, `warehouse`) VALUES (?, ?) " +
                     "ON DUPLICATE KEY UPDATE `warehouse` = VALUES(`warehouse`)")) {

            preparedStatement.setInt(1, warehouse.city.getObjectUUID());
            preparedStatement.setString(2, warehouseJSON.toString());

            return (preparedStatement.executeUpdate() > 0);

        } catch (SQLException e) {
            Logger.error(e);
        }
        return false;
    }

    public void LOAD_WAREHOUSES() {

        try (Connection connection = DbManager.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_warehouse`;");
             ResultSet rs = preparedStatement.executeQuery()) {

            while (rs.next()) {
                int cityUID = rs.getInt("cityUUID");
                JSONObject jsonObject = new JSONObject(rs.getString("warehouse"));
                City city = City.getCity(cityUID);

                if (city == null) {
                    Logger.error("No city " + cityUID + " for warehouse");
                    continue;
                }

                city.warehouse = new Warehouse(jsonObject);
                city.warehouse.city = city;

                // Locate warehouse building
                for (Building building : city.parentZone.zoneBuildingSet) {
                    if (building.getBlueprint().getBuildingGroup().equals(mbEnums.BuildingGroup.WAREHOUSE)) {
                        city.warehouse.building = building;
                        break;
                    }
                }

            }

        } catch (Exception e) {
            Logger.error(e);
        }
    }

    public boolean WRITE_WORKORDER(WorkOrder workOrder) {

        JSONObject warehouseJSON = WorkOrder.toJson(workOrder);

        try (Connection connection = DbManager.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `dyn_workorders` (`workorderID`, `workorder`) VALUES (?, ?) " +
                     "ON DUPLICATE KEY UPDATE `workorder` = VALUES(`workorder`)")) {

            preparedStatement.setInt(1, workOrder.workOrderID);
            preparedStatement.setString(2, warehouseJSON.toString());

            return (preparedStatement.executeUpdate() > 0);

        } catch (SQLException e) {
            Logger.error(e);
        }
        return false;
    }

    public void DELETE_WORKORDER(WorkOrder workOrder) {
        try (Connection connection = DbManager.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM `dyn_workorders` WHERE `workorderID` = ?;")) {
            preparedStatement.setInt(1, workOrder.workOrderID);
            preparedStatement.executeUpdate();

        } catch (SQLException e) {
            Logger.error(e);
        }

    }

    public void LOAD_WORKORDERS() {

        // Method loads NPC workOrders from disk at bootstrap.
        // A workOrder will persist until completed or junked
        // via the client interface.

        ArrayList<WorkOrder> submitList = new ArrayList<>();
        ArrayList<WorkOrder> orphanList = new ArrayList<>();

        try (Connection connection = DbManager.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM `dyn_workorders`;");
             ResultSet rs = preparedStatement.executeQuery()) {

            while (rs.next()) {
                JSONObject jsonObject = new JSONObject(rs.getString("workorder"));
                WorkOrder workOrder = new WorkOrder(jsonObject);
                submitList.add(workOrder);
            }
        } catch (Exception e) {
            Logger.error(e);
        }

        // Submit new workOrders to the ForgeManager

        for (WorkOrder workOrder : submitList) {

            DbManager.WarehouseQueries.DELETE_WORKORDER(workOrder);

            // Delete but do not reconstitute orphan workOrders

            if (workOrder.vendor == null)
                continue;

            workOrder.workOrderID = ForgeManager.workOrderCounter.incrementAndGet();
            DbManager.WarehouseQueries.WRITE_WORKORDER(workOrder);
            ForgeManager.vendorWorkOrderLookup.get(workOrder.vendor).add(workOrder);
            ForgeManager.forge.add(workOrder);
        }

    }
}
