const charactersSet = require('../src/datasets/got/characters.json')
const genderSet = require('../src/datasets/got/genders.json')
const groupSet = require('../src/datasets/got/groups.json')
const fs = require('fs')
const generateUuid = require('uuid').v4

const findCharacterGender = name => (genderSet.male.includes(name) ? 'male' : 'female')

const findCharacterGroup = name => groupSet.groups.find(group => group.characters.includes(name))
const findCharacter = name =>
  charactersSet.characters.find(character => character.characterName === name)

const getGroupName = group => (group !== undefined ? group.name : 'no group')

const onlyUnique = (value, index, self) => self.indexOf(value) === index

;(async () => {
  let dataset = {
    nodes: [],
    links: []
  }
  let characterNames = []
  const relationships = ['killed', 'parentOf', 'siblings', 'marriedEngaged', 'allies', 'abducted']

  // build an array of characters involved
  relationships.forEach(function(relationship) {
    charactersSet.characters.forEach(function(character) {
      if (character.hasOwnProperty(relationship)) {
        characterNames.push(character.characterName)
        character[relationship].forEach(function(v) {
          characterNames.push(v)
        })
      }
    })
  })

  characterNames = characterNames.filter(onlyUnique).sort()
  dataset.nodes = characterNames.map((character, id) => {
    const data = findCharacter(character)
    return {
      id,
      uuid: generateUuid(),
      name: character,
      label: character,
      gender: findCharacterGender(character),
      group: getGroupName(findCharacterGroup(character)),
      dataClass: 'person',
      type: 'regular',
      royal: data !== undefined ? data.royal : false,
      kingsguard: data !== undefined ? data.kingsguard : false
    }
  })

  // build list of links based on position in array of characters
  relationships.forEach(function(relationship) {
    charactersSet.characters.forEach(function(character) {
      if (character.hasOwnProperty(relationship)) {
        character[relationship].forEach(function(v) {
          const source = characterNames.indexOf(v)
          const target = characterNames.indexOf(character.characterName)
          if (source === target) return
          dataset.links.push({
            uuid: generateUuid(),
            source,
            target,
            description: relationship,
            direction: false,
            id: Math.floor(Math.random() * 1000000000)
          })
        })
      }
    })
  })

  // dataset.links = dataset.links.filter(
  //   lLink =>
  //     !dataset.links.find(rLink => rLink.source === lLink.target || rLink.target === lLink.source)
  // )
  fs.writeFile(
    'src/datasets/got.dataset.js',
    `/* eslint-disable */\nexport default ${JSON.stringify(dataset, null, 2)}`,
    'utf8',
    () => {}
  )
})()
