import buildings from "./data/buildings";
import { NAMES } from "./data/heroes";
import { Hex } from "./hexgrid";
import type { BuildingSource, BuildingType, HeroType, QuestType, ResourcesType } from "./types";
import { getEmptyResources, random, shuffle } from "./utils";


let uid = 0;


export function getBuildingSource(buildingType: string): BuildingSource {
    const source: BuildingSource | undefined = buildings.find(b => b.type === buildingType);

    if (source === undefined) {
        throw new Error(`Unknown building type: "${buildingType}"`);
    }

    return source
}


export function createBuilding(buildingType: string): BuildingType {
    const source: BuildingSource = getBuildingSource(buildingType);

    return {
        ...source,
        id: uid++,
        level: 1,
        tile: new Hex(0, 0),
        state: {
            upgrade: {
                isUpgrading: false,
                remainingTime: 0,
            }
        },
    };
}


export function createQuest(level: number): QuestType {
    const reward = getEmptyResources();
    const adjustedLevel = level * level + 3;
    const duration = random(adjustedLevel - 2, adjustedLevel + 2);
    Object.keys(reward).forEach(r => {
        const resource = r as keyof ResourcesType;
        reward[resource] = random(
            Math.round((duration * 5 - level * 10) * (1 + level / 3)),
            Math.round((duration * 5 + level * 10) * (1 + level / 3)),
        );

        if (resource === 'culture') {
            reward[resource] = Math.round(reward[resource] / 20);
        }
    });

    return {
        id: uid++,
        duration,
        reward,
        level,
        started: false,
    };
}


export function createHero(): HeroType {
    return {
        id: uid++,
        name: shuffle(NAMES)[0],
    };
}
