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


package engine.db.handlers;

import engine.Enum;
import engine.Enum.GameObjectType;
import engine.Enum.TransactionType;
import engine.gameManager.DbManager;
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.simple.JSONObject;
import org.json.simple.parser.JSONParser;
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, Enum.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 boolean UPDATE_WAREHOUSE(Warehouse warehouse) {

        JSONObject warehouseJSON = new JSONObject(warehouse.resources);

        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() {

        JSONParser jsonParser = new JSONParser();

        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 = (JSONObject) jsonParser.parse(rs.getString("warehouse"));
                City city = City.getCity(cityUID);
                city.warehouse = new Warehouse(jsonObject);

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

            }

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