import {ItemGroupCharacteristic} from "../../game-model/inventory/ItemgroupCharacteristic";
import {ItemGroup} from "../../game-model/inventory/ItemGroup";
import {InventorySlot} from "../../game-model/inventory/intentory-slots/InventorySlot";
import {InventorySlotSerializer} from "../../serializer/InventorySlotSerializer";
import {InventoryCharacteristic} from "../../game-model/inventory/intentory-slots/InventoryCharacteristic";

export class InventorySlotParser {
  private parsedCharacteristics: ItemGroupCharacteristic[]
  private parsedItemgroups: ItemGroup[]


  constructor(parsedCharacteristics: ItemGroupCharacteristic[], parsedItemgroups: ItemGroup[]) {
    this.parsedCharacteristics = parsedCharacteristics;
    this.parsedItemgroups = parsedItemgroups;
  }

  parseInventorySlots(inventorySlotData: any): InventorySlot[] {
    const result: InventorySlot[] = []
    for(let i=0; i<inventorySlotData.length; i++) {
      result.push(this.parseSingleInventorySlot(inventorySlotData[i]))
    }
    return result;
  }

  private parseSingleInventorySlot(inventorySlotData: any): InventorySlot {
    const slotName = inventorySlotData.slotName;
    const slotCharacteristics = this.parseSlotCharacteristics(inventorySlotData.slotCharacteristics)
    const inheritedGroups = this.parseRequieredInheritedItemgroups(inventorySlotData.requiredInheritances);

    const inventorySlot = new InventorySlot(slotName);
    inventorySlot.slotCharacteristics = slotCharacteristics;
    inventorySlot.requiredInheritances = inheritedGroups;
    inventorySlot.combinable = inventorySlotData.combinable;

    return inventorySlot;
  }

  private parseSlotCharacteristics(slotCharacteristicsData: any): InventoryCharacteristic[] {
    const characteristics: InventoryCharacteristic[] = []
    for(let i=0; i<slotCharacteristicsData.length; i++) {
      const increasingCharacteristic = this.findReferencedCharacteristic(slotCharacteristicsData[i].increasingCharacteristic);
      const decreasingCharacteristic = this.findReferencedCharacteristic(slotCharacteristicsData[i].decreasingCharacteristic);
      characteristics.push(new InventoryCharacteristic(increasingCharacteristic!, decreasingCharacteristic!))
    }
    return characteristics;
  }

  private parseRequieredInheritedItemgroups(inheritanceData: any): ItemGroup[] {
    const result: ItemGroup[] = []
    for(let i=0; i<inheritanceData.length; i++) {
      const inheritedGroup = this.findReferencedItemgroup(inheritanceData[i]);
      if(inheritedGroup != undefined) {
        result.push(inheritedGroup);
      }
    }
    return result;
  }

  private findReferencedCharacteristic(characteristicName: string) {
    return this.parsedCharacteristics.find(characteristic => characteristic.characteristicName === characteristicName);
  }

  private findReferencedItemgroup(groupName: string) {
    return this.parsedItemgroups.find(group => group.componentName === groupName);
  }
}