import { configuration } from "./configuration.js";
import { emitEvent } from "./events.js";
import { registerLoadCallback } from "./main.js";
import { getPlannerCellDom, getPlannerDom } from "./planner.js";
import { findFullEntry } from "./ncpf-utils.js";

registerLoadCallback(() => {
});

const solverMetadata = {};
let solverMetadataCounter = 0;
function createSolverMetadata(data) {
  const id = solverMetadataCounter;
  solverMetadata[id] = data;
  solverMetadataCounter++;
  return id;
}
export function setSolverMetadata(domNode, data) {
  if (domNode.dataset.solverMetadata) {
    solverMetadata[Number(domNode.dataset.solverMetadata)] = data;
    return;
  }
  domNode.dataset.solverMetadata = createSolverMetadata(data).toString(10);
}
export function getSolverMetadata(id) {
  if (typeof id === "object") {
    // assume DOM element
    if (id.dataset && id.dataset.solverMetadata) {
      return getSolverMetadata(id.dataset.solverMetadata);
    }
    return null;
  }
  if (typeof id === "string") {
    return getSolverMetadata(Number(id));
  }
  return solverMetadata[id];
}
export function deleteSolverMetadata(id) {
  if (typeof id === "object") {
    // assume DOM object
    if (id.dataset && id.dataset.solverMetadata) {
      return deleteSolverMetadata(id.dataset.solverMetadata);
    }
  }
  delete solverMetadata[id];
}

export function resetSolver(design = undefined, designConfiguration) {
  const planner = getPlannerDom();
  if (design && designConfiguration) {
    planner.dataset.type = design.type;
    if (design.type === "nuclearcraft:overhaul_sfr") {
      // design has coolant_recipe and block_recipes
      const designCoolantRecipe = designConfiguration.coolant_recipes[design.coolant_recipe];
      const fullCoolantRecipe = findFullEntry(
          "coolant_recipes",
          designCoolantRecipe,
          { configurationHint: design.type },
      );
      setSolverMetadata(planner, { coolant_recipe: fullCoolantRecipe });

      const designBlockRecipes = design.block_recipes.flat(3);
      for (let x = 0; x < design.dimensions[0]; x++) {
        for (let y = 0; y < design.dimensions[1]; y++) {
          for (let z = 0; z < design.dimensions[2]; z++) {
            const block = designConfiguration.blocks[design.design[x][y][z]];
            if (!block || !block.modules || !block.modules["ncpf:block_recipes"]) continue;
            const blockRecipeIndex = designBlockRecipes.shift();
            const blockRecipe = block.modules["ncpf:block_recipes"].recipes[blockRecipeIndex];
            setSolverMetadata(getPlannerCellDom(x, y, z), { block_recipe: blockRecipe });
          }
        }
      }
    }
  }

  emitEvent("solver:reset:done");
}
