/**
 * Modify front-matter.
 *
 * Some keys are included by Hexo, please don't use them.
 * e.g. layout title date updated comments tags categories permalink keywords
 *
 * Some keys are generated by Hexo, don't use them either.
 * e.g. content excerpt more source full_source path permalink prev next raw photos link
 */

/* global hexo */

'use strict';

const keys = ['toc', 'reward_settings', 'quicklink'];

function showWarnLog(source, variable) {
  hexo.log.warn(`front-matter: '${variable}' has deprecated, source: ${source}`);
  hexo.log.warn('see: https://github.com/theme-next/hexo-theme-next/pull/1211');
}

function compatibleBeforeAssign(page) {
  if (page.quicklink === true) {
    page.quicklink = {enable: true};
    showWarnLog(page.source, 'quicklink:true');
  }
  if (page.quicklink === false) {
    page.quicklink = {enable: false};
    showWarnLog(page.source, 'quicklink:true');
  }
}

function compatibleAfterAssign(page) {
  if (page.reward !== undefined) {
    page.reward_settings.enable = page.reward;
    showWarnLog(page.source, 'reward');
  }
  if (page.toc_number !== undefined) {
    page.toc.number = page.toc_number;
    showWarnLog(page.source, 'toc_number');
  }
  if (page.toc_max_depth !== undefined) {
    page.toc.max_depth = page.toc_max_depth;
    showWarnLog(page.source, 'toc_max_depth');
  }
}

hexo.extend.filter.register('template_locals', locals => {
  const { page, theme } = locals;

  compatibleBeforeAssign(page);

  keys.forEach(key => {
    page[key] = Object.assign({}, theme[key], page[key]);
  });

  compatibleAfterAssign(page);

  // Set default value for toc.max_depth
  if (!page.toc.max_depth) {
    page.toc.max_depth = 6;
  }

  // Set home or archive quicklink
  if (page.__index) {
    page.quicklink.enable = theme.quicklink.home;
  }
  if (page.archive) {
    page.quicklink.enable = theme.quicklink.archive;
  }
});
