import * as  path from 'path'
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'
import { logger as _logger } from '@plastichub/core/debug'
export const logger = _logger('ph-site')
import { createContent, ICompileTaskOptions } from '@plastichub/osr-tasks/tasks/compile'
import { productHugoTask, readProducts, registerProductTasks } from './product'
import { OSRL_MODULE_NAME, LANGUAGES, I18N_STORE, OSR_ROOT, TRANSLATE_CONTENT, TASK_COMPILE_CONTENT_CACHE, RETAIL_DEFAULT_BRANCH, I18N_SOURCE_LANGUAGE, REGISTER_RETAIL_TASKS, TASK_COMPILE_CONTENT } from './config'
import { writeTaskConfig } from './log'
import * as pMap from 'p-map'

// const _logger = createSubLogger(logger, logLevel, 'compile:content')

export const grunt = (grunt) => {
  grunt.loadNpmTasks("grunt-extend-config")
  const logLevel = grunt.option('logLevel') || 'warn'
  logger.setSettings({ minLevel: logLevel })
  const watch = grunt.option('watchContent')
  //  Pages - src/content/lang/**/*.md
  
  const contentTask = (sourceLanguage, options: any = {}) => {
    const config = {}
    const src = `src/content/${sourceLanguage}/**/*.md`
    const cwd = process.cwd()
    const dst = path.resolve(`${cwd}/content/${sourceLanguage}`)
    const profile = path.resolve(`./.osrl.json`)
    const root = path.resolve(`./src/content/${sourceLanguage}`)
    const compilerOptions: ICompileTaskOptions = {
      output: dst,
      debug: false,
      cache: !!grunt.option('cache') || TASK_COMPILE_CONTENT_CACHE,
      watchContent: watch,
      module: OSRL_MODULE_NAME,
      profile,
      root,
      ...(options || {}),
      env: 'library',
      language: 'osr',
      format: 'html',
      sourceLanguage: sourceLanguage,
      logLevel: logLevel,
      variables: {
        cwd,
        targetLanguage: sourceLanguage,
        sourceLanguage: sourceLanguage,
        i18n: I18N_STORE(OSR_ROOT(), sourceLanguage)
      }
    }
    let defaultOptions = {
      src: [src],
      options: compilerOptions
    }
    const onCompiled = (src, dst, content) => content
    const onCompiledDone = async (src, dst, options, content) => {
      return await pMap(LANGUAGES, async (dstLanguage) => {
        const opts: ICompileTaskOptions = {
          ...defaultOptions.options,
          output: path.resolve(`${process.cwd()}/content/${dstLanguage}/`),
          sourceLanguage: sourceLanguage,
          targetLanguage: dstLanguage,
          variables: {
            ...defaultOptions.options.variables,
            cwd: process.cwd(),
            i18n: I18N_STORE(OSR_ROOT(), dstLanguage),
            sourceLanguage: sourceLanguage,
            targetLanguage: dstLanguage,
          }
        };
        const content = await createContent(src, opts)
        return content
      }, { concurrency: 1 })
    }
    config[`content-${sourceLanguage}`] = {
      ...defaultOptions,
      options: {
        ...defaultOptions.options,
        onCompiled: TRANSLATE_CONTENT ? onCompiled : undefined,
        onCompileDone: TRANSLATE_CONTENT ? onCompiledDone : undefined
      }
    }
    grunt.extendConfig({ compile: config })
    grunt.registerTask(`content-${sourceLanguage}`, `compile:content-${sourceLanguage}`)
    writeTaskConfig(`compile_content-${sourceLanguage}`, config)
  }
  grunt.initConfig({
    pkg: grunt.file.readJSON("package.json"),
    compile: {}
  })
  contentTask(I18N_SOURCE_LANGUAGE)
  grunt.registerTask('content', ['compile:content-en'])

  ////////////////////////////////////////////////////////////
  //  Products
  const product_item_tasks = []
  const productTasks = (items) =>
    items.forEach((i) => productHugoTask(grunt, i, {}, product_item_tasks))

  const _products = readProducts(grunt.option('branch') || RETAIL_DEFAULT_BRANCH)
  TASK_COMPILE_CONTENT && productTasks(_products)
  REGISTER_RETAIL_TASKS && registerProductTasks(grunt)
  require("@plastichub/osr-tasks").initConfig(grunt, {})
}
module.exports = grunt
