import {PlayerCharacterDataModel} from "./module/data/character.mjs";
import {SkillSheet} from "./module/sheets/skillSheet.mjs";
import {SpellSheet} from "./module/sheets/spellSheet.mjs";
import {SkillDataModel} from "./module/data/skill.mjs";
import {SpellDataModel} from "./module/data/spell.mjs";
import {VornachteileDataModel} from "./module/data/vornachteile.mjs";
import {Character} from "./module/documents/character.mjs";
import {CharacterSheet} from "./module/sheets/characterSheet.mjs";
import {VornachteilSheet} from "./module/sheets/vornachteilSheet.mjs";
import {GroupDataModel} from "./module/data/group.mjs";
import {GroupSheet} from "./module/sheets/groupSheet.mjs";
import {EquipmentDataModel} from "./module/data/equipment.mjs";
import {AusruestungSheet} from "./module/sheets/equipmentSheet.mjs";
import {CreatureDataModel} from "./module/data/creature.mjs";
import {CreatureSheet} from "./module/sheets/creatureSheet.mjs";
import {LiturgySheet} from "./module/sheets/liturgySheet.mjs";
import {LiturgyDataModel} from "./module/data/liturgy.mjs";
import {BlessingDataModel} from "./module/data/blessing.mjs";
import {SpecialAbilityDataModel} from "./module/data/specialAbility.mjs";
import {SpecialAbilitySheet} from "./module/sheets/specialAbilitySheet.mjs";
import {ActiveEffectSheet} from "./module/sheets/ActiveEffectSheet.mjs";
import {ActiveEffectDataModel} from "./module/data/activeeffect.mjs";

async function preloadHandlebarsTemplates() {
    return loadTemplates([
        // ui partials.
        'systems/DSA_4-1/templates/ui/partial-rollable-button.hbs',
        'systems/DSA_4-1/templates/ui/partial-rollable-weaponskill-button.hbs',
        'systems/DSA_4-1/templates/ui/partial-attribute-button.hbs',
        'systems/DSA_4-1/templates/ui/partial-talent-editable.hbs',
        'systems/DSA_4-1/templates/ui/partial-die.hbs',
        'systems/DSA_4-1/templates/ui/partial-advantage-button.hbs',
        'systems/DSA_4-1/templates/ui/partial-sf-button.hbs',
        'systems/DSA_4-1/templates/ui/partial-action-button.hbs',
        'systems/DSA_4-1/templates/ui/partial-equipment-button.hbs',
        'systems/DSA_4-1/templates/ui/partial-equipment-group-button.hbs',
        'systems/DSA_4-1/templates/ui/partial-array-editor.hbs',
        'systems/DSA_4-1/templates/dialog/modify-liturgy.hbs'
    ]);
}

Hooks.once("init", () => {

    game.DSA41 = {
        rollItemMacro
    }

    // Configure custom Document implementations.
    CONFIG.Actor.documentClass = Character;

    // Configure System Data Models.
    CONFIG.Actor.dataModels = {
        character: PlayerCharacterDataModel,
        group: GroupDataModel,
        creature: CreatureDataModel,
    };

    CONFIG.Item.dataModels = {
        Skill: SkillDataModel,
        Spell: SpellDataModel,
        Advantage: VornachteileDataModel,
        Equipment: EquipmentDataModel,
        Liturgy: LiturgyDataModel,
        Blessing: BlessingDataModel,
        SpecialAbility: SpecialAbilityDataModel,
        ActiveEffect: ActiveEffectDataModel,
    }

    CONFIG.Combat.initiative = {
        formula: `(@ini.wuerfel)d6 + @ini.aktuell`,
        decimals: 0
    }

    console.log("DSA 4.1 is ready for development!")

    Actors.registerSheet('dsa41.character', CharacterSheet, {
        types: ["character"],
        makeDefault: true,
        label: 'DSA41.CharacterLabels.Item'
    })
    Actors.registerSheet('dsa41.creature', CreatureSheet, {
        types: ["creature"],
        makeDefault: true,
        label: 'DSA41.CreatureLabel.Item'
    })
    Actors.registerSheet('dsa41.group', GroupSheet, {
        types: ["group"],
        makeDefault: true,
        label: 'DSA41.GroupLabel.Item'
    })

    // Register sheet application classes
    Items.registerSheet('dsa41.skill', SkillSheet, {
        types: ["Skill"],
        makeDefault: true,
        label: 'DSA41.SkillLabels.Item',
    });
    Items.registerSheet('dsa41.spell', SpellSheet, {
        types: ["Spell"],
        makeDefault: true,
        label: 'DSA41.SpellLabels.Item',
    });
    Items.registerSheet('dsa41.advantage', VornachteilSheet, {
        types: ["Advantage"],
        makeDefault: true,
        label: 'DSA41.VornachteilLabels.Item'
    })
    Items.registerSheet('dsa41.equipment', AusruestungSheet, {
        types: ["Equipment"],
        makeDefault: false,
        label: 'DSA41.AusruestungLabels.Item'
    })
    Items.registerSheet('dsa41.liturgy', LiturgySheet, {
        types: ["SpecialAbility"],
        makeDefault: true,
        label: 'DSA41.SpecialAbilityLabels.Item'
    })
    Items.registerSheet('dsa41.specialAbility', SpecialAbilitySheet, {
        types: ["Liturgy"],
        makeDefault: true,
        label: 'DSA41.LiturgyLabels.Item'
    })

    Items.registerSheet('dsa41.activeEffect', ActiveEffectSheet, {
        types: ['ActiveEffect'],
        makeDefault: true,
        label: 'DSA41.ActiveEffectLabels.ActiveFfect'
    })

    return preloadHandlebarsTemplates();
})

Hooks.on('dropActorSheetData', (actor, sheet, data) => {
    if (data.uuid) {
        if (actor.type === "character") {
            return CharacterSheet.onDroppedData(actor, sheet, data);
        } else {
            return GroupSheet.onDroppedData(actor, sheet, data);
        }
    }
})

Hooks.once("ready", async function () {
    // Wait to register hotbar drop hook on ready so that modules could register earlier if they want to
    Hooks.on("hotbarDrop", (bar, data, slot) => createBoilerplateMacro(data, slot));
});

async function createBoilerplateMacro(data, slot) {
    console.log(data, slot)
    if (data.type !== "Item") return;
    if (!("data" in data)) return ui.notifications.warn("You can only create macro buttons for owned Items");
    const item = data.data;

    // Create the macro command
    const command = `game.DSA41.rollItemMacro("${item.name}");`;
    let macro = game.macros.entities.find(m => (m.name === item.name) && (m.command === command));
    if (!macro) {
        macro = await Macro.create({
            name: item.name,
            type: "script",
            img: item.img,
            command: command,
            flags: {"dsa41.itemMacro": true}
        });
    }
    game.user.assignHotbarMacro(macro, slot);
    return false;
}

function rollItemMacro(itemName) {
    const speaker = ChatMessage.getSpeaker();
    let actor;
    if (speaker.token) actor = game.actors.tokens[speaker.token];
    if (!actor) actor = game.actors.get(speaker.actor);
    const item = actor ? actor.items.find(i => i.name === itemName) : null;
    if (!item) return ui.notifications.warn(`Your controlled Actor does not have an item named ${itemName}`);

    // Trigger the item roll
    return item.roll();
}
