import Logger from "../../utils/Logger"
import M5Character, { M5Attribute } from "../actors/M5Character"

export default class M5CharacterSheet extends ActorSheet {

	static get defaultOptions() {
		return mergeObject(super.defaultOptions, {
			template: "systems/midgard5/templates/sheets/character/main.hbs",
			width: 600,
			height: 400,
			classes: ["midgard5", "sheet", "character"],
			tabs: [{ navSelector: ".sheet-navigation", contentSelector: ".sheet-content", initial: "base_values" }]
		})
	}

	// get template() {
	// 	return "systems/midgard5/templates/character_sheet/main.hbs"
	// }Options extends ActorSheet.Options = ActorSheet.Options, Data extends object = ActorSheet.Data<Options>

	override getData(options?: Partial<ActorSheet.Options>): ActorSheet.Data<ActorSheet.Options> | Promise<ActorSheet.Data<ActorSheet.Options>> {
		const actor = this.actor as M5Character
		//console.log("Sheet getData", (actor as any).data)
		return Promise.resolve(super.getData(options)).then(context => {
			actor.prepareDerivedData()

			const actorData = (actor as any).data.toObject(false)
			context.actor = actorData;
			context.data = actorData.data;
		
			//console.log("Sheet Promise", context)
			return context
		})
	}

	override activateListeners(html: JQuery) {
		super.activateListeners(html)

		html.find(".roll-button").on("click", async (event) => {
			const row = event.target.parentElement
			let skillName = row.dataset["skill"]

			const actor = this.actor as M5Character
			const context = this.actor.data
			const data = context.data

			const skill = data.skills.general[skillName]
			const attribute = data.attributes[skill.attribute]
			console.log(skill, attribute)

			const r = new Roll("1d20 + @fw + @bonus", {
				fw: skill.fw + 12,
				bonus: M5Character.attributeBonus(attribute)
			})
			await r.evaluate().then(value => {
				const skillLocalized = (game as Game).i18n.localize("midgard5." + skillName)
				const chatString = skillLocalized + ": " + value.result + " = " + value.total
				//console.log(chatString)
	
				const speaker = ChatMessage.getSpeaker({actor: actor})
				let chatData = { content: (game as Game).i18n.format(chatString, {name: (actor as any).name}), speaker }
				ChatMessage.applyRollMode(chatData, (r.options as any).rollMode)
				return ChatMessage.create(chatData)
			})
		})
	}
}
