foundryvtt-reve-de-dragon/module/time/rdd-calendrier.js

434 lines
15 KiB
JavaScript
Raw Normal View History

import { MAX_NOMBRE_ASTRAL, RdDTimestamp, WORLD_TIMESTAMP_SETTING } from "./rdd-timestamp.js";
import { RdDCalendrierEditor } from "./rdd-calendrier-editor.js";
import { RdDResolutionTable } from "../rdd-resolution-table.js";
import { RdDUtility } from "../rdd-utility.js";
import { RdDDice } from "../rdd-dice.js";
import { Misc } from "../misc.js";
import { DialogChronologie } from "../dialog-chronologie.js";
import { HIDE_DICE, SYSTEM_RDD, SYSTEM_SOCKET_ID } from "../constants.js";
2023-06-20 23:43:24 +02:00
import { ReglesOptionnelles } from "../settings/regles-optionnelles.js";
import { DialogChateauDormant } from "../sommeil/dialog-chateau-dormant.js";
import { APP_ASTROLOGIE_REFRESH, AppAstrologie } from "../sommeil/app-astrologie.js";
import { AutoAdjustDarkness } from "./auto-adjust-darkness.js";
const TEMPLATE_CALENDRIER = "systems/foundryvtt-reve-de-dragon/templates/time/calendar.hbs";
const INITIAL_CALENDAR_POS = { top: 200, left: 200, horlogeAnalogique: true };
2020-09-20 16:36:39 +02:00
/* -------------------------------------------- */
export class RdDCalendrier extends Application {
static init() {
game.settings.register(SYSTEM_RDD, "liste-nombre-astral", {
name: "liste-nombre-astral",
scope: "world",
config: false,
default: [],
type: Object
});
2020-12-08 21:40:41 +01:00
game.settings.register(SYSTEM_RDD, "calendrier-pos", {
name: "calendrierPos",
scope: "client",
config: false,
default: INITIAL_CALENDAR_POS,
type: Object
});
}
static get defaultOptions() {
2024-05-01 09:13:21 +02:00
return foundry.utils.mergeObject(super.defaultOptions, {
title: "Calendrier",
template: TEMPLATE_CALENDRIER,
classes: ["calendar"],
popOut: true,
resizable: false,
width: 'fit-content',
height: 'fit-content',
});
}
2021-07-09 01:01:12 +02:00
constructor() {
super();
this.timestamp = RdDTimestamp.getWorldTime();
if (Misc.isUniqueConnectedGM()) { // Uniquement si GM
RdDTimestamp.setWorldTime(this.timestamp);
this.rebuildNombresAstraux(); // Ensure always up-to-date
}
Hooks.on('updateSetting', async (setting, update, options, id) => this.onUpdateSetting(setting, update, options, id));
}
get title() {
const calendrier = this.timestamp.toCalendrier();
return `${calendrier.heure.label}, ${calendrier.jourDuMois} ${calendrier.mois.label} ${calendrier.annee} (${calendrier.mois.saison})`;
}
savePosition() {
game.settings.set(SYSTEM_RDD, "calendrier-pos", {
top: this.position.top,
left: this.position.left,
horlogeAnalogique: this.horlogeAnalogique
});
}
getSavePosition() {
const pos = game.settings.get(SYSTEM_RDD, "calendrier-pos");
if (pos?.top == undefined) {
return INITIAL_CALENDAR_POS;
}
this.horlogeAnalogique = pos.horlogeAnalogique;
return pos
}
setPosition(position) {
super.setPosition(position)
this.savePosition()
}
display() {
AutoAdjustDarkness.adjust(RdDTimestamp.getWorldTime().darkness);
const pos = this.getSavePosition()
this.render(true, { left: pos.left, top: pos.top });
return this;
}
_getHeaderButtons() {
if (game.user.isGM) {
return [
{ class: "calendar-astrologie", icon: "fa-solid fa-moon-over-sun", onclick: ev => this.showAstrologieEditor() },
{ class: "calendar-set-datetime", icon: "fa-solid fa-calendar-pen", onclick: ev => this.showCalendarEditor() },
]
}
return []
}
2023-05-25 13:17:16 +02:00
async close() { }
async onUpdateSetting(setting, update, options, id) {
if (setting.key == SYSTEM_RDD + '.' + WORLD_TIMESTAMP_SETTING) {
this.timestamp = RdDTimestamp.getWorldTime();
this.positionAiguilles()
this.render(false);
Hooks.callAll(APP_ASTROLOGIE_REFRESH)
}
if (setting.key == SYSTEM_RDD + '.' + "liste-nombre-astral") {
Hooks.callAll(APP_ASTROLOGIE_REFRESH)
}
2020-12-08 21:40:41 +01:00
}
getData() {
const formData = super.getData();
this.fillCalendrierData(formData);
return formData;
}
/* -------------------------------------------- */
fillCalendrierData(formData = {}) {
2024-05-01 09:13:21 +02:00
foundry.utils.mergeObject(formData, this.timestamp.toCalendrier());
formData.isGM = game.user.isGM;
formData.heures = RdDTimestamp.definitions()
formData.horlogeAnalogique = this.horlogeAnalogique;
formData.autoDarkness = AutoAdjustDarkness.isAuto()
return formData;
}
/* -------------------------------------------- */
/** @override */
async activateListeners(html) {
super.activateListeners(html);
this.html = html;
this.html.find('.ajout-chronologie').click(ev => DialogChronologie.create());
this.html.find('.toggle-horloge-analogique').click(ev => this.onToggleHorlogeAnalogique())
this.html.find('.toggle-auto-darkness').click(ev => this.onToggleAutoDarkness())
this.html.find('.calendar-btn').click(ev => this.onCalendarButton(ev));
this.html.find('.horloge-roue .horloge-heure').click(event => {
const h = this.html.find(event.currentTarget)?.data('heure');
this.positionnerHeure(Number(h));
})
this.html.find('.calendar-set-datetime').click(ev => {
ev.preventDefault();
this.showCalendarEditor();
});
this.html.find('.calendar-astrologie').click(ev => {
ev.preventDefault();
this.showAstrologieEditor();
2021-07-09 01:01:12 +02:00
});
this.positionAiguilles()
}
positionAiguilles() {
const timestamp = this.getTimestamp();
this.html.find(`div.horloge-roue div.horloge-aiguille-heure img`).css(Misc.cssRotation(timestamp.angleHeure));
this.html.find(`div.horloge-roue div.horloge-aiguille-minute img`).css(Misc.cssRotation(timestamp.angleMinute));
}
onToggleHorlogeAnalogique() {
this.horlogeAnalogique = !this.horlogeAnalogique;
this.savePosition()
this.display()
}
/* -------------------------------------------- */
getNombresAstraux() {
return game.settings.get(SYSTEM_RDD, "liste-nombre-astral") ?? []
}
async setNombresAstraux(nombresAstraux) {
await game.settings.set(SYSTEM_RDD, "liste-nombre-astral", nombresAstraux)
2020-12-08 21:40:41 +01:00
}
2020-12-08 23:28:29 +01:00
2020-12-10 20:14:35 +01:00
/* -------------------------------------------- */
dateCourante() {
return this.timestamp.formatDate();
2020-12-10 20:14:35 +01:00
}
dateReel() {
return new Date().toLocaleString("sv-SE", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit"
});
}
isAfterIndexDate(indexDate) {
// TODO: standardize
return indexDate < this.timestamp.indexDate;
2021-04-04 18:37:16 +02:00
}
2021-01-16 18:54:07 +01:00
/* -------------------------------------------- */
heureCourante() { return RdDTimestamp.definition(this.timestamp.heure); }
2021-01-16 18:54:07 +01:00
2020-12-09 00:01:02 +01:00
/* -------------------------------------------- */
getCurrentMinute() { return this.timestamp.indexMinute; }
getTimestamp() {
return this.timestamp;
}
getTimestampFinChateauDormant(nbJours = 0) {
return this.timestamp.nouveauJour().addJours(nbJours);
}
getTimestampFinHeure(nbHeures = 0) {
return this.timestamp.nouvelleHeure().addHeures(nbHeures);
2020-12-09 00:01:02 +01:00
}
2021-04-04 18:37:16 +02:00
/* -------------------------------------------- */
getIndexFromDate(jour, mois) {
const addYear = mois < this.timestamp.mois || (mois == this.timestamp.mois && jour < this.timestamp.jour)
const time = RdDTimestamp.timestamp(this.timestamp.annee + (addYear ? 1 : 0), mois, jour);
return time.indexDate;
2021-04-04 18:37:16 +02:00
}
2020-12-12 23:31:19 +01:00
/* -------------------------------------------- */
getJoursSuivants(count) {
return Misc.intArray(this.timestamp.indexDate, this.timestamp.indexDate + count)
.map(i => { return { label: RdDTimestamp.formatIndexDate(i), index: i } })
2020-12-12 23:31:19 +01:00
}
2020-12-08 23:28:29 +01:00
/* -------------------------------------------- */
async ajouterNombreAstral(indexDate) {
const nombreAstral = await RdDDice.rollTotal("1dh", { showDice: HIDE_DICE, rollMode: "selfroll" });
2020-12-08 23:28:29 +01:00
return {
nombreAstral: nombreAstral,
lectures: [],
index: indexDate
2020-12-08 23:28:29 +01:00
}
}
2021-04-25 10:08:40 +02:00
/* -------------------------------------------- */
async resetNombresAstraux() {
await Promise.all(game.actors.filter(it => it.type == "personnage").map(async it => await it.deleteNombresAstraux()))
await this.setNombresAstraux([])
2021-04-25 10:08:40 +02:00
}
/**
*
* @param {*} indexDate la date pour laquelle obtenir le nombre astral. Si undefined, on prend la date du jour
* @returns le nombre astral pour la date, ou pour la date du jour si la date n'est pas fournie.
* Si aucun nombre astral n'est trouvé, retourne 0 (cas où l'on demanderait un nombre astral en dehors des 12 jours courant et à venir)
*/
getNombreAstral(indexDate = undefined) {
if (indexDate == undefined) {
indexDate = this.timestamp.indexDate;
}
const nombresAstraux = this.getNombresAstraux()
let astralData = nombresAstraux.find(it => it.index == indexDate);
return astralData?.nombreAstral ?? 0;
2020-12-12 23:31:19 +01:00
}
2020-12-08 23:28:29 +01:00
/* -------------------------------------------- */
async rebuildNombresAstraux() {
if (Misc.isUniqueConnectedGM()) {
const nombresAstraux = this.getNombresAstraux()
let newNombresAstraux = [];
2021-06-09 00:00:15 +02:00
for (let i = 0; i < MAX_NOMBRE_ASTRAL; i++) {
let dayIndex = this.timestamp.indexDate + i;
let na = nombresAstraux.find(it => it.index == dayIndex);
2021-06-09 00:00:15 +02:00
if (na) {
newNombresAstraux[i] = na;
} else {
newNombresAstraux[i] = await this.ajouterNombreAstral(dayIndex);
}
}
game.actors.filter(it => it.isPersonnage()).forEach(actor => actor.supprimerAnciensNombresAstraux());
await this.setNombresAstraux(newNombresAstraux);
2020-12-08 23:28:29 +01:00
}
}
2021-06-09 16:38:52 +02:00
/* -------------------------------------------- */
async setNewTimestamp(newTimestamp) {
const oldTimestamp = this.timestamp;
await Promise.all(game.actors.map(async actor => await actor.onTimeChanging(oldTimestamp, newTimestamp)));
RdDTimestamp.setWorldTime(newTimestamp);
2023-06-20 23:43:24 +02:00
if (oldTimestamp.indexDate + 1 == newTimestamp.indexDate && ReglesOptionnelles.isUsing("chateau-dormant-gardien")) {
await DialogChateauDormant.create();
}
this.timestamp = newTimestamp;
await this.rebuildNombresAstraux();
this.positionAiguilles()
this.display();
2020-12-08 23:28:29 +01:00
}
2020-12-08 21:40:41 +01:00
/* -------------------------------------------- */
async onCalendarButton(ev) {
ev.preventDefault();
const calendarAvance = ev.currentTarget.attributes['data-calendar-avance'];
const calendarSet = ev.currentTarget.attributes['data-calendar-set'];
if (calendarAvance) {
await this.incrementTime(Number(calendarAvance.value));
2022-12-29 02:31:29 +01:00
}
else if (calendarSet) {
this.positionnerHeure(Number(calendarSet.value));
2020-12-08 21:40:41 +01:00
}
this.positionAiguilles()
}
/* -------------------------------------------- */
async incrementTime(minutes = 0) {
if (game.user.isGM) {
await this.setNewTimestamp(this.timestamp.addMinutes(minutes));
Hooks.callAll(APP_ASTROLOGIE_REFRESH);
}
2020-12-08 21:40:41 +01:00
}
2020-12-08 23:28:29 +01:00
/* -------------------------------------------- */
2021-07-09 01:01:12 +02:00
async incrementerJour() {
await this.setNewTimestamp(this.timestamp.nouveauJour());
2020-12-08 23:28:29 +01:00
}
2020-12-08 21:40:41 +01:00
/* -------------------------------------------- */
async positionnerHeure(heure) {
if (game.user.isGM) {
const indexDate = this.timestamp.indexDate;
const addDay = this.timestamp.heure < heure ? 0 : 1;
const newTimestamp = new RdDTimestamp({ indexDate: indexDate + addDay }).addHeures(heure);
await this.setNewTimestamp(newTimestamp)
Hooks.callAll(APP_ASTROLOGIE_REFRESH);
}
2020-12-08 21:40:41 +01:00
}
2020-12-12 23:31:19 +01:00
/* -------------------------------------------- */
getLectureAstrologieDifficulte(dateIndex) {
let indexNow = this.timestamp.indexDate;
2020-12-12 23:31:19 +01:00
let diffDay = dateIndex - indexNow;
return - Math.floor(diffDay / 2);
}
/* -------------------------------------------- */
async requestNombreAstral(request) {
2022-12-29 02:31:29 +01:00
const actor = game.actors.get(request.id);
if (Misc.isUniqueConnectedGM()) { // Only once
console.log(request);
let jourDiff = this.getLectureAstrologieDifficulte(request.date);
2022-06-12 12:14:55 +02:00
let niveau = Number(request.astrologie.system.niveau) + Number(request.conditions) + Number(jourDiff) + Number(request.etat);
let rollData = {
2020-12-17 00:05:32 +01:00
caracValue: request.carac_vue,
finalLevel: niveau,
showDice: HIDE_DICE,
rollMode: "blindroll"
};
await RdDResolutionTable.rollData(rollData);
request.rolled = rollData.rolled;
2022-12-29 02:31:29 +01:00
request.isValid = request.rolled.isSuccess;
request.nbAstral = this.getNombreAstral(request.date);
2022-12-29 02:31:29 +01:00
if (request.rolled.isSuccess) {
if (request.rolled.isPart) {
2022-12-29 02:31:29 +01:00
// Gestion expérience (si existante)
2023-10-23 23:37:47 +02:00
request.competence = actor.getCompetence('Astrologie')
2022-12-29 02:31:29 +01:00
request.selectedCarac = actor.system.carac["vue"];
actor.appliquerAjoutExperience(request, 'hide');
}
}
else {
request.nbAstral = await RdDDice.rollTotal("1dhr" + request.nbAstral, {
rollMode: "selfroll", showDice: HIDE_DICE
});
2020-12-12 23:31:19 +01:00
}
// Mise à jour des nombres astraux du joueur
await this.addNbAstralJoueur(actor, request.date, request.nbAstral, request.isValid)
Hooks.callAll(APP_ASTROLOGIE_REFRESH)
game.socket.emit(SYSTEM_SOCKET_ID, { msg: "msg_app_astrologie_refresh", data: {} })
2020-12-12 23:31:19 +01:00
}
}
async addNbAstralJoueur(actor, date, nbAstral, isValid) {
const nombresAstraux = this.getNombresAstraux()
const astralData = nombresAstraux.find(it => it.index == date)
if (astralData) {
astralData.lectures.push({ actorId: actor.id, nombreAstral: nbAstral });
await this.setNombresAstraux(nombresAstraux);
await actor.ajouteNombreAstral(date, nbAstral, isValid);
}
2022-12-29 02:31:29 +01:00
}
2020-12-11 16:19:19 +01:00
/* -------------------------------------------- */
getAjustementAstrologique(heureNaissance, name = undefined) {
const defHeure = RdDTimestamp.findHeure(heureNaissance);
if (defHeure) {
return RdDTimestamp.ajustementAstrologiqueHeure(defHeure.heure, this.getNombreAstral(), this.timestamp.heure);
}
else if (name) {
2021-01-16 18:54:07 +01:00
ui.notifications.warn(name + " n'a pas d'heure de naissance, ou elle est incorrecte : " + heureNaissance);
2020-12-11 03:23:34 +01:00
}
2021-06-09 00:00:15 +02:00
else {
ui.notifications.warn(heureNaissance + " ne correspond pas à une heure de naissance");
}
2020-12-11 03:23:34 +01:00
return 0;
}
2020-12-08 21:40:41 +01:00
/* -------------------------------------------- */
async saveEditeur(calendrierData) {
const newTimestamp = RdDTimestamp.timestamp(
Number.parseInt(calendrierData.annee),
calendrierData.mois.heure,
Number.parseInt(calendrierData.jourMois),
calendrierData.heure.heure,
Number.parseInt(calendrierData.minutes)
);
await this.setNewTimestamp(newTimestamp);
2020-12-08 21:40:41 +01:00
}
2020-12-08 21:40:41 +01:00
/* -------------------------------------------- */
async showCalendarEditor() {
const calendrierData = this.fillCalendrierData();
if (this.editeur == undefined) {
const html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/time/calendar-editor.hbs', calendrierData);
this.editeur = new RdDCalendrierEditor(html, this, calendrierData)
2020-12-08 21:40:41 +01:00
}
this.editeur.updateData(calendrierData);
2020-12-08 21:40:41 +01:00
this.editeur.render(true);
}
2020-12-10 20:14:35 +01:00
/* -------------------------------------------- */
async showAstrologieEditor() {
await AppAstrologie.create();
2020-12-10 20:14:35 +01:00
}
async onToggleAutoDarkness() {
await AutoAdjustDarkness.toggle()
this.display()
}
}