// SPDX-FileCopyrightText: 2021 Johannes Loher
//
// SPDX-License-Identifier: MIT

'use strict';

import { packageName } from './config';
import logger from './logger';
import { getBrightRadius, getDimRadius, updateSource } from './wrappers/token';
import { getHeaderButtons } from './wrappers/token-config';
import { libWrapper } from './shims/libWrapperShim';

export default function registerForHooks() {
  Hooks.once('init', onInit);
  Hooks.on('updateScene', onUpdateScene);
  Hooks.on('updateToken', onUpdateToken);
}

function onInit() {
  logger.info(`Initializing ${packageName}`);

  const dimRadiusTarget = 'CONFIG.Token.objectClass.prototype.dimRadius';
  try {
    libWrapper.register(packageName, dimRadiusTarget, getDimRadius, 'OVERRIDE');
  } catch (e) {
    logger.warn(`Failed to override ${dimRadiusTarget}, some things might not work correctly:`, e);
  }

  const brightRadiusTarget = 'CONFIG.Token.objectClass.prototype.dimRadius';
  try {
    libWrapper.register(packageName, brightRadiusTarget, getBrightRadius, 'OVERRIDE');
  } catch (e) {
    logger.warn(`Failed to override ${brightRadiusTarget}, some things might not work correctly:`, e);
  }

  libWrapper.register(packageName, 'CONFIG.Token.objectClass.prototype.updateSource', updateSource, 'WRAPPER');

  libWrapper.register(packageName, 'CONFIG.Token.sheetClass.prototype._getHeaderButtons', getHeaderButtons, 'WRAPPER');
}

function onUpdateScene(scene, change) {
  if (change.darkness != null) {
    scene.getEmbeddedCollection('Token').forEach((tokenDocument) => tokenDocument.object.updateSource());
  }
}

function onUpdateToken(token, change) {
  const shouldUpdateSource = [
    'dimVisionDarknessMin',
    'dimVisionDarknessMax',
    'brightVisionDarknessMin',
    'brightVisionDarknessMax',
  ].some((flagKey) => `flags.darkness-dependent-vision.${flagKey}` in foundry.utils.flattenObject(change));
  if (shouldUpdateSource) {
    token.object.updateSource();
  }
}