const fs = require('fs')

const oldFontsJson = fs.readFileSync(`${__dirname}/old.json`).toString()

let result = `/*
# This file is auto-generated! To update run:
# node fe/scripts/fonts/generateFontsJson.js
#
# We're keeping the generator around rather than just replacing fonts.json,
# because we might need to use more data from the Google webfonts json
# in the future. We can get rid of the fe/scripts/fonts stuff if we decide
# that fonts.json is stable.
#
# If we ever want to save file size on this we could remove cssFallback
# and always use category to determine what fallback to use.
#
# name: always lowercase. universal font identifier.
# displayName: what the user sees. must capitalize.
# cssValue: what gets set into font-family property. specify fallbacks!
# settings: weights for google, etc
# hidden: some old/bad fonts are deprecated - which means they are loaded but no longer selectable
# isSuggested: whether the font shows up in the initial list or only in search
#              ===> be careful with adding new suggested fonts! v3 editor needs to
#                   load the webfont file
*/
`

currentFonts = eval(oldFontsJson)
currentFonts.push({
  name: 'helvetica',
  displayName: 'Helvetica',
  cssValue: 'helvetica, arial',
  cssFallback: 'sans-serif',
  disableBody: false,
  fontType: 'system',
  settings: null,
  hidden: false,
  isSuggested: false,
},
// These fonts were removed from the list provided by the google fonts API,
// but we still need them in the list because people are already using them
{
  "name": "amatica sc",
  "displayName": "Amatica SC",
  "cssValue": "\"amatica sc\"",
  "cssFallback": "sans-serif",
  "disableBody": true,
  "fontType": "google",
  "settings": {
      "google_embed_name": "Amatica SC"
  },
  "hidden": false,
  "isSuggested": false
},
{
  "name": "droid sans",
  "displayName": "Droid Sans",
  "cssValue": "\"droid sans\"",
  "cssFallback": "sans-serif",
  "disableBody": false,
  "fontType": "google",
  "settings": null,
  "hidden": false,
  "isSuggested": false
},
{
  "name": "droid sans mono",
  "displayName": "Droid Sans Mono",
  "cssValue": "\"droid sans mono\"",
  "cssFallback": "sans-serif",
  "disableBody": false,
  "fontType": "google",
  "settings": null,
  "hidden": false,
  "isSuggested": false
},
{
  "name": "droid serif",
  "displayName": "Droid Serif",
  "cssValue": "\"droid serif\"",
  "cssFallback": "serif",
  "disableBody": false,
  "fontType": "google",
  "settings": null,
  "hidden": false,
  "isSuggested": false
},
{
  "name": "ek mukta",
  "displayName": "Ek Mukta",
  "cssValue": "\"ek mukta\"",
  "cssFallback": "sans-serif",
  "disableBody": false,
  "fontType": "google",
  "settings": null,
  "hidden": false,
  "isSuggested": false
})

// Usually blacklisted because they have many similar variations
const blacklistedFonts = [
  'Slabo 13px',
  'Slabo 27px',
  'Baloo Bhai',
  'Baloo Bhaina',
  'Baloo Chettan',
  'Baloo Da',
  'Baloo Paaji',
  'Baloo Tamma',
  'Baloo Thambi',
  'Hind Guntur',
  'Hind Madurai',
  'Hind Siliguri',
  'Hind Vadodara',
].map(n => n.toLowerCase())


const newSuggestedFonts = [
  'Unna',
  'Bad Script',
  'IBM Plex Serif',
  'IBM Plex Sans',
  'Roboto Slab',
  'PT Serif',
  'PT Sans',
  'Libre Baskerville',
  'Vidaloka',
  'Share Tech',
  'Changa One',
  'Zilla Slab Highlight',
  'Limelight',
  'Bungee'
]

const fontsToDisableInBody = [
  'Vidaloka',
  'Share Tech',
  'Changa One',
  'Zilla Slab Highlight',
  'Limelight',
  'Bungee'
]

const fontsToReenableAsBody = ['lato']

fontsToRemoveFromSuggested = ['dosis', 'arapey', 'quando', 'trocchi']
fontsToUnhide = ['arapey', 'quando', 'trocchi']

googleFonts = JSON.parse(fs.readFileSync(`${__dirname}/googleFonts.json`)).items
/* eslint-disable max-statements */
googleFonts.forEach((font, i) => {
  const name = font.family.toLowerCase()
  const existingFontItem = currentFonts.filter(f => f.name === name)[0]
  if (existingFontItem) {
    if (fontsToRemoveFromSuggested.indexOf(existingFontItem.name) !== -1) {
      existingFontItem.isSuggested = false
    }
    if (fontsToUnhide.indexOf(existingFontItem.name) !== -1) {
      existingFontItem.hidden = false
    }
    if (fontsToReenableAsBody.indexOf(existingFontItem.name) !== -1) {
      existingFontItem.disableBody = false
    }

    // Keep value from existing manually curated list of fonts
    return
  }
  if (blacklistedFonts.indexOf(font.family.toLowerCase()) !== -1) {
    console.log('font blacklisted:', font.family)
    return
  }

  if (font.subsets.indexOf('latin') === -1) {
    // console.log("Excluding font b/c no latin", font.family)
    return
  }

  const fallback = {
    'sans-serif': 'sans-serif',
    serif: 'serif',
    handwriting: 'cursive',
    display: 'sans-serif',
    monospace: 'sans-serif',
  }[font.category]
  if (!fallback) {
    console.log('No fallback for font: ', font)
  }
  const newFont = {
    name,
    displayName: font.family,
    cssValue: `"${name}"`,
    cssFallback: fallback,
    disableBody: font.category === 'display' || fontsToDisableInBody.includes(font.family),
    fontType: 'google',
    settings: null,
    hidden: false,
    isSuggested: newSuggestedFonts.indexOf(font.family) !== -1,
    // "category": font.category
  }

  if (font.variants.indexOf('regular') === -1) {
    // some fonts don't have a regular font, and won't load
    // if you don't specify a specific weight
    if (!newFont.settings) {
      newFont.settings = {}
    }
    newFont.settings.weight = font.variants.join(',')
    console.log(font.family)
  }

  let canAutogenerateEmbedName = true
  // We try to auto-generate the embed by capitalizing the first
  // character of each word, but that doesn't work for fonts like
  // "PT Something", so store the embed name explicitly
  if (/[A-Z]{2,10}/.test(font.family)) {
    canAutogenerateEmbedName = false
  }
  // e.g. "Waiting for the Sunrise"
  if (/ [a-z]/.test(font.family)) {
    canAutogenerateEmbedName = false
  }
  // e.g. "BenchNine"
  if (/[A-Z][a-z]+[A-Z]/.test(font.family)) {
    canAutogenerateEmbedName = false
  }
  // e.g. "permanent marker"
  if (/(^[^A-Z])|( [a-z])/.test(font.family)) {
    canAutogenerateEmbedName = false
  }
  if (!canAutogenerateEmbedName) {
    if (!newFont.settings) {
      newFont.settings = {}
    }
    newFont.settings.google_embed_name = font.family
  }
  currentFonts.push(newFont)
})
/* eslint-enable max-statements */

result += JSON.stringify(currentFonts, null, 4)
fs.writeFileSync('./config/fonts.json', result)
