const fs = require('fs')
const path = require('path')
const fse = require('fs-extra')
const { execSync } = require('child_process')

const usage = '\nbuild <vn.n.n[-pre[.n]]> | <HEAD> [-p]\n'
const versionsFile = path.resolve(__dirname, './versions.json')
const { outputPath, publicPath } = require('../config')

const args = process.argv
if (args.length < 3) {
  console.log(usage, '\n')
  process.exit()
}

const version = args[2]
const versions = JSON.parse(fs.readFileSync(path.resolve(__dirname, versionsFile), 'utf8'))
const versionIsHEAD = version === 'HEAD'
const useForcePush = args[3] === '-p'
const versionNumber = versionIsHEAD ? (
  `v${JSON.parse(fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf8')).version}`
) : version

function execSyncWithLog(command) {
  console.log(command)
  try {
    execSync(command, { stdio: 'inherit' })
  } catch (error) {
    console.error(error.output[1])
    process.exit(error.status)
 }
}

fse.copySync(
  path.resolve(__dirname, '../public'),
  path.resolve(__dirname, '../../')
)

function saveVersionsFile() {
  if (!versions.includes(versionNumber)) {
    versions.push(versionNumber)
    versions.sort()
    fs.writeFileSync(versionsFile, JSON.stringify(versions, null, 2), 'utf8')
    execSyncWithLog(`git add ${versionsFile} && git commit -m "add ${versionNumber} to versions file"`)
  }
}

function savePublicVersionsFile() {
  const publicVersionsFile = path.resolve(__dirname, '../../versions.json')
  if (fs.existsSync(publicVersionsFile)) {
    const publicVersions = JSON.parse(fs.readFileSync(publicVersionsFile, 'utf8'))
    if (!publicVersions.includes(versionNumber)) {
      publicVersions.push(versionNumber)
      publicVersions.sort()
    }
    fs.writeFileSync(publicVersionsFile, JSON.stringify(publicVersions, null, 2), 'utf8')
  } else {
    fs.writeFileSync(publicVersionsFile, JSON.stringify(versions, null, 2), 'utf8')
  }
}

function buildDocs() {
  process.chdir(__dirname)
  execSyncWithLog('git checkout gh-pages')
  execSyncWithLog('git reset --hard HEAD')

  if (versionIsHEAD) {
    execSyncWithLog('git checkout master')
  } else {
    execSyncWithLog(`git checkout tags/${version}`)
  }

  execSyncWithLog('test -d \"./build\" && rm -r \"./build\" || exit 0')
  execSyncWithLog('cd ../../ && npm install && cd docs && npm run build')
  execSyncWithLog('git checkout gh-pages')

  if (versionIsHEAD) {
    const replaceHTML = fs.readFileSync('../build/index.html', 'utf8').replace(/\/static\//gim, '/HEAD/static/')
    fs.writeFileSync(
      path.resolve(__dirname, '../../index.html'),
      replaceHTML,
      'utf8'
    )
    fse.copySync(
      path.resolve(__dirname, '../build'),
      path.resolve(__dirname, '../../HEAD')
    )
    replaceWebpackPublicPath('HEAD')
  }

  fse.moveSync(
    path.resolve(__dirname, '../build'),
    path.resolve(__dirname, `../../${versionNumber}`)
  )
  replaceWebpackPublicPath(versionNumber)

  if (versionIsHEAD) {
    fs.writeFileSync(
      path.resolve(__dirname, '../../release'),
      `./${versionNumber}`
    )
  }
  savePublicVersionsFile()

  execSyncWithLog(`git add ../../ && git commit -m 'Update ${version}' Docs`)

  execSyncWithLog(`git push${useForcePush ? ' -f' : ''}`)
}

function replaceWebpackPublicPath(versionNumb) {
  const versionHTMLFile = `../../${versionNumb}/index.html`
  const replaceHTML = fs.readFileSync(versionHTMLFile, 'utf8').replace(/\/static\//gim, `/${versionNumb}/static/`)
  fs.writeFileSync(
    versionHTMLFile,
    replaceHTML,
    'utf8'
  )

  const webpackManifestFile = path.join(
    __dirname,
    `../../${versionNumb}/${publicPath}`,
    'webpack-manifest.json'
  )
  const commonJSName = JSON.parse(fs.readFileSync(webpackManifestFile, 'utf8'))['common.js']
  const commonJSFile = path.join(
    __dirname,
    `../../${versionNumb}`,
    publicPath,
    commonJSName
  )
  const replaceJS = fs.readFileSync(commonJSFile, 'utf8').replace(/\/static\//gim, `/${versionNumb}/static/`)
  fs.writeFileSync(
    commonJSFile,
    replaceJS,
    'utf8'
  )
}

saveVersionsFile()
buildDocs()

@@ -2544,32 +2544,8 @@
     
- path.resolve(__dirname,
  '..
@@ -2559,17 +2559,16 @@
 ex.html'
-)
 ,%0A      
@@ -2601,57 +2601,164 @@
     
+ 
+ 
 )%0A    
-fse.copySync(%0A      path.resolve(__dirname,
+const buildDocsFolder = '../../HEAD'%0A    if (fs.existsSync(buildDocsFolder)) %7B%0A      fse.emptyDirSync(buildDocsFolder)%0A    %7D%0A    fse.copySync(%0A     
  '..
@@ -2764,25 +2764,24 @@
 ./build'
-)
 ,%0A      
 path.res
@@ -2776,45 +2776,23 @@
     
-path.resolve(__dirname, '../../HEAD')
+buildDocsFolder
 %0A   
@@ -2842,49 +2842,158 @@
 %0A%0A  
-fse.moveSync(%0A    path.resolve(__dirname,
+const buildDocsFolder = %60../../$%7BversionNumber%7D%60%0A  if (fs.existsSync(buildDocsFolder)) %7B%0A    fse.emptyDirSync(buildDocsFolder)%0A  %7D%0A  fse.moveSync(%0A   
  '..
@@ -3003,64 +3003,29 @@
 ild'
-)
 ,%0A    
-path.resolve(__dirname, %60../../$%7BversionNumber%7D%60)
+buildDocsFolder
 %0A  )
@@ -3223,24 +3223,27 @@
 onsFile()%0A%0A 
+ //
  execSyncWit
@@ -3307,18 +3307,20 @@
  Docs%60)%0A
-%0A
  
+ //
  execSyn

update build script