'use strict'

const fs = require('fs')
const path = require('path')

const rimraf = require('rimraf')
const chalk = require('chalk')

const console = require('../helpers/color-console')
const sfs = require('../helpers/sfs')
const {installWatcher} = require('../helpers/watcher')

const {build, getBuildFolder} = require('./builder')
const loader = require('./loader')

const {assetsToCopy} = require('../assets')
const config = require('../config')

// -------------------------------------------------------------
// Module.
// -------------------------------------------------------------

function generate (dataPath) {
  console.log(`Starting directory: ${chalk.green(dataPath)}`)

  const presskits = findData(dataPath)

  if (countDataFiles(presskits) === 0) {
    console.log('')
    console.warn('No data files found!')
    return
  }

  generateHTML(dataPath, presskits)
  exportAssets(dataPath)

  console.log('')
  console.log('Done! 👌')

  if (config.watch) {
    // Delete the assets (CSS/etc.) and install watchers.
    rimraf(path.join(dataPath, 'build/css'), () => {
      showHeader('Watching files')
      installWatcher(dataPath, generateHTML.bind(null, dataPath, presskits))
    })
  }
}

function findData (dataPath) {
  showHeader('Finding data')

  const presskits = {products: []}

  // Inspect given path for data files and get all correct ones.
  let files = sfs.findAllFiles(dataPath, { maxDepth: 1, ignoredFolders: ['build', 'node_modules'] })

  files.filter(isDataFile).forEach(file => {
    try {
      let presskit = loader.loadDataFile(file)
      if (!presskit) return

      console.log(`- ${presskit.type}: "${presskit.title}" ${chalk.dim(file)}`)

      if (presskit.type === 'company') {
        if (presskits.company) {
          console.warn('Multiple companies detected. This is not supported yet, only the last will be used!')
        }

        presskits.company = { path: dataPath, presskit: presskit }
      } else {
        presskits.products.push({ path: file, presskit: presskit })
      }
    } catch (err) {
      console.error(err)
    }
  })

  return presskits
}

function generateHTML (dataPath, presskits) {
  showHeader('Generating HTML')

  const productsList = []

  for (const product of presskits.products) {
    const outputPath = build(
      dataPath,
      product.path,
      product.presskit,
      {company: presskits.company.presskit}
    )

    productsList.push({path: outputPath, title: product.presskit.title})
  }

  // Company should be the last one, listing all the products
  if (presskits.company) {
    // Notice that we provide a ref to all the products here.
    build(
      dataPath,
      presskits.company.path,
      presskits.company.presskit,
      {products: productsList}
    )
  }
}

function exportAssets (dataPath) {
  showHeader('Exporting assets')

  // Copy assets (CSS and stuff)
  copyMandatoryFiles(dataPath)
}

// Print a console UI header text.
function showHeader (text) {
  console.log('')
  console.log(chalk.yellow(text + '…'))
}

// Add css and any mandatory files specified to the build directory
function copyMandatoryFiles (basePath) {
  let buildDir = getBuildFolder(basePath)

  for (let f of assetsToCopy) {
    let filepath = path.resolve(f)
    let filename = path.basename(filepath)
    let dir = path.basename(path.dirname(filepath))

    let targetDir = path.join(buildDir, dir)
    sfs.createDir(targetDir)

    let targetPath = path.join(targetDir, filename)

    console.log('- ' + targetPath)
    fs.writeFileSync(targetPath, fs.readFileSync(filepath))
  }
}

// Count the number of products/company in the presskit.
function countDataFiles (presskits) {
  let count = 0
  count += (presskits.company ? 1 : 0)
  count += presskits.products.length

  return count
}

// Is a file qualifying to be a data file? ie. `data.xml`.
// We don't check the content here, just the name.
function isDataFile (filename) {
  var ext = path.extname(filename)
  filename = path.basename(filename, ext)

  return filename === 'data' && ext === '.xml'
}

// -------------------------------------------------------------
// Exports.
// -------------------------------------------------------------

module.exports = {
  generate
}

@@ -2144,23 +2144,19 @@
 aPath, p
-resskit
+age
 s) %7B%0A  s
@@ -2237,23 +2237,19 @@
 uct of p
-resskit
+age
 s.produc
@@ -2351,16 +2351,25 @@
 %0A      %7B
+%0A        
 company:
@@ -2370,23 +2370,19 @@
 mpany: p
-resskit
+age
 s.compan
@@ -2391,16 +2391,24 @@
 presskit
+,%0A      
 %7D%0A    )%0A
@@ -2551,31 +2551,27 @@
 ucts%0A  if (p
-resskit
+age
 s.company) %7B
@@ -2659,39 +2659,35 @@
 ataPath,%0A      p
-resskit
+age
 s.company.path,%0A
@@ -2689,31 +2689,27 @@
 ath,%0A      p
-resskit
+age
 s.company.pr
@@ -2723,16 +2723,25 @@
 %0A      %7B
+%0A        
 products
@@ -2754,16 +2754,24 @@
 uctsList
+,%0A      
 %7D%0A    )%0A

Rename presskits to pages in generateHTML()