const targetClassName = 'sight-line-target',
  activeClassName = 'active';

function cubeDistance(a, b) {
  return Math.max(Math.abs(a.q - b.q), Math.abs(a.r - b.r), Math.abs(a.s - b.s));
}

function cubeRound({ q, r, s }) {
  let rQ = Math.round(q),
    rR = Math.round(r),
    rS = Math.round(s);

  const q_diff = Math.abs(rQ - q),
    r_diff = Math.abs(rR - r),
    s_diff = Math.abs(rS - s);

  if (q_diff > r_diff && q_diff > s_diff) {
    rQ = -rR - rS;
  } else if (r_diff > s_diff) {
    rR = -rQ - rS;
  } else {
    rS = -rQ - rR;
  }

  return { q: rQ, r: rR, s: rS };
}

function lerp(a, b, t) {
  return a + (b - a) * t;
}

function cubeLerp(a, b, t) {
  return { q: lerp(a.q, b.q, t), r: lerp(a.r, b.r, t), s: lerp(a.s, b.s, t) };
}

function lock(sightLine, cell) {
  sightLine.classList.remove(activeClassName);
  cell.classList.add(targetClassName);

  return cell;
}

function unlock(sightLine, lockTarget) {
  sightLine.classList.add(activeClassName);
  lockTarget.classList.remove(targetClassName);

  return null;
}

let sightLine, lockTarget,
  activeHexes = [];

export function create({ x: x1, y: y1 }, { x: x2, y: y2 }) {
  const line = document.createElementNS(svgns, 'line');
  sightLine = line;

  line.classList.add('sight-line');
  line.classList.add(activeClassName);
  line.setAttributeNS(null, 'x1', x1);
  line.setAttributeNS(null, 'y1', y1);
  line.setAttributeNS(null, 'x2', x2);
  line.setAttributeNS(null, 'y2', y2);

  return line;
}

export function calcIndexes(a, b) {
  const N = cubeDistance(a, b);
  const results = [];

  for (let i = 0; i <= N; i++) {
    results.push(cubeRound(cubeLerp(a, b, 1.0 / N * i)));
  }

  return results;
}

export function clear() {
  sightLine && sightLine.remove();
  sightLine = null;

  lockTarget && lockTarget.classList.remove(targetClassName);
  lockTarget = null;
}

export function update({ x, y }) {
  sightLine.setAttributeNS(null, 'x1', x);
  sightLine.setAttributeNS(null, 'y1', y);
}

export function toggleLock(cell) {
  lockTarget = lockTarget ? unlock(sightLine, lockTarget) : lock(sightLine, cell);
}

export function getSightLine() {
  return sightLine;
}

export function getLockTarget() {
  return lockTarget;
}

export function setHexes(hexes) {
  activeHexes.forEach(h => h.classList.remove(activeClassName));
  hexes.forEach(h => h.classList.add(activeClassName));
  activeHexes = hexes;
}
