import { insertLinkWithMultilinkUpdate, arrGetNewId } from '@/store/modules/data/helpers.js'
import { sample, random } from 'lodash'

export function generateDataset(nodeCount, linkCount) {
  const nodes = [],
    links = []

  for (let n = 0; n < nodeCount; n++) {
    nodes.push({
      id: n,
      name: getSampleFirstName() + ' Chalupová-Tročkova',
      dataClass: 'person',
      type: 'regular',
      label: getSampleFirstName(),
      vis: { graph: { x: 0, y: 0 } }
    })
  }
  const lastNodeId = nodeCount - 1

  let linksCreated = 0
  let sourceId = 0,
    targetId = lastNodeId
  for (let n = 0; n < linkCount; n++) {
    linksCreated += addLink(links, sourceId, targetId, 40)
    if (random(0, 100) < 40) sourceId++
    if (random(0, 100) < 40) targetId--
    if (sourceId === targetId) sourceId++
    if (sourceId > lastNodeId || targetId > lastNodeId || targetId < 0) break
  }

  sourceId = 0
  targetId = lastNodeId
  for (let n = linkCount + 1; n < linkCount + 50; n++) {
    linksCreated += addLink(links, sourceId, targetId, 60)
    if (random(0, 100) < 50) sourceId += random(0, 4)
    if (random(0, 100) < 30) targetId += random(0, 4)
    if (sourceId === targetId) sourceId++
    if (sourceId > lastNodeId || targetId > lastNodeId || targetId < 0) break
  }

  while (linksCreated < linkCount) {
    let sourceId = random(lastNodeId)
    let targetId = 0
    while (targetId === sourceId) targetId = random(lastNodeId)
    linksCreated += addLink(links, sourceId, targetId, 50)
  }

  return { nodes: nodes, links: links }
}

function addLink(links, sourceId, targetId, isDirectionalChance) {
  let link = {
    id: arrGetNewId(links),
    source: sourceId,
    target: targetId,
    direction: random(0, 100) < isDirectionalChance,
    description: getSampleLinkDescription()
  }
  if (insertLinkWithMultilinkUpdate(link, links, sourceId, arrGetNewId(links) + 1)) return 2
  return 1
}

function getSampleFirstName() {
  return sample([
    'Anna',
    'Alexandra',
    'Daniela',
    'Čestmír',
    'Anton',
    'Igor',
    'Katarína',
    'Vincent',
    'Lívia',
    'Miloslava',
    'Mikuláš',
    'David',
    'Henrieta',
    'Ema',
    'Irena'
  ])
}

function getSampleLinkDescription() {
  return sample([
    'killed',
    'teaches',
    'used',
    'friend',
    'spouse',
    'family',
    'business connections',
    'lived together',
    'transferred money to'
  ])
}
