const got = require('got')
const csv = require('csv-parse/lib/sync')
const fs = require('fs')
const path = require('path')
const { execSync } = require('child_process')

const kgInfoApi = `https://interactive-viewer.apps.hbp.eu/datasets/kgInfo`
const ngRoot = `https://neuroglancer.humanbrainproject.eu/precomputed/difumo/pmaps/`
const outputPath = path.join(__dirname, '../../output/taxonomy_metadata')
const inputPath = path.join(__dirname, '../../input')

const datasets = [
  ['DiFuMo atlas (64 dimensions)',   'https://kg.ebrains.eu/search/instances/Dataset/e472a8c7-d9f9-4e75-9d0b-b137cecbc6a2'],
  ['DiFuMo atlas (128 dimensions)',  'https://kg.ebrains.eu/search/instances/Dataset/b8d0ba16-5543-4594-a6f0-ecbacfc9fb04'],
  ['DiFuMo atlas (256 dimensions)',  'https://kg.ebrains.eu/search/instances/Dataset/5438792c-ff2a-4554-9f85-af795f870741'],
  ['DiFuMo atlas (512 dimensions)',  'https://kg.ebrains.eu/search/instances/Dataset/2ab064dd-7ac5-44ca-8711-a72435f0672e'],
  ['DiFuMo atlas (1024 dimensions)', 'https://kg.ebrains.eu/search/instances/Dataset/164ef5c9-bec5-43c7-b258-80798cb0d57b']
]

const getKgId = fullId => {
  const re = /\/([a-f0-9-]*)$/.exec(fullId)
  return re && re[1]
} 

const kgIds = datasets.map(arr => {
  const re = /\(([0-9]*)\sdimensions\)$/.exec(arr[0])
  return {
    key: re[1],
    kgId: getKgId(arr[1])
  }
})

const getKgInfo = async kgId => {
  const resp = await got(kgInfoApi, {
    responseType: 'json',
    searchParams: {
      kgSchema: 'minds/core/dataset/v1.0.0',
      kgId
    }
  })
  return resp.body
}

const main = async () => {
  for (const {kgId, key} of kgIds) {
    const r = await getKgInfo(kgId)
    const labelFile = r.files.find(file => /^labels_[0-9]*_dictionary\.csv$/.test(file.name))
    if (!labelFile) throw new Error('labelFile not found')

    const { body: labelFileContent } = await got(labelFile.absolutePath, { responseType: 'text' })
    const arr = csv(labelFileContent, {
      comment: '#',
      columns: true
    })
    
    const regions = []
    const files = []
    for (const { Component, Difumo_names, ...rest } of arr) {

      /**
       * region metadata to be interpreted by the viewer
       */
      const region = {
        name: Difumo_names,
        labelIndex: Component,
        originDatasets: [
          {
            kgId,
            kgSchema: 'minds/core/dataset/v1.0.0',
            filename: `${Component}.nii.gz`
          }
        ],
        ontologyMetadata: rest
      }
      regions.push(region)

      /**
       * preview metadata to be interpreted by viewer and kg previewer data
       */

      const volumeMetadata = JSON.parse(fs.readFileSync(
        path.join(outputPath, '../metadata', key, `${Number(Component) - 1}.nii.gz.json`),
        'utf-8'
      ))

       const file = {
         filename: `${Component}.nii.gz`,
         mimetype: 'application/nifti',
         url: `${ngRoot}${key}/${Component}.nii.gz`,
         referenceSpaces: [
          {
            name: "MNI 152 ICBM 2009c Nonlinear Asymmetric",
            fullId: "minds/core/referencespace/v1.0.0/dafcffc5-4826-4bf1-8ff6-46b8a31ff8e2"
          }
        ],
        volumeMetadata
       }
       files.push(file)
    }

    /**
     * iterated over all files, now write to json
     */
    fs.writeFileSync(
      path.join(outputPath, 'datasetpreview_metadata',  kgId),
      JSON.stringify(files, null, 2),
      'utf-8'
    )

    const difumoParcellation = {
      name: `DiFuMo Atlas (${key} dimensions)`,
      ngId: `DiFuMo Atlas (${key} dimensions)`,
      auxillaryMeshIndices: [
        65535
      ],
      originDatasets: [
        {
          kgSchema: "minds/core/dataset/v1.0.0",
          kgId
        }
      ],
      regions
    }
    fs.writeFileSync(
      path.join(outputPath, 'taxonomy_metadata', `difumo_${key}.json`),
      JSON.stringify(difumoParcellation, null, 2),
      'utf-8'
    )
  }
}

execSync(`rm -rf ${outputPath}/*`)

execSync(`mkdir -p ${outputPath}/taxonomy_metadata`)
execSync(`mkdir -p ${outputPath}/datasetpreview_metadata`)


main()