import * as firingArc from './game/firing_arc.js';
import * as sightLine from './game/sight_line.js';
import * as soldier from './game/soldier.js';
import { Observable } from "./observable";

let svg,
  placing = [];

const top = {
  collection: new Map()
};

function getCellContents(cell) {
  return cell.querySelectorAll('*:not(use[href="#hex"])');
}

function getGridIndex({ parentElement: { dataset: { q, r, s, t }}}) {
  return { q: +q, r: +r, s: +s, t: +t };
}

function getHex(cell) {
  return cell.querySelector('use[href="#hex"]');
}

function getCellOccupant(cell) {
  return cell.querySelector('.counter') || svg.querySelector('.grid-top .counter');
}

function getCells(svg) {
  return svg.querySelectorAll('[data-q][data-r][data-s][data-t]');
}

function getLockedSightLine(svg) {
  return svg.querySelector('line.sight-line:not(.active)');
}

function getActiveSightLine(svg) {
  return svg.querySelector('line.sight-line.active');
}

function isCounter(el) {
  const regex = new RegExp('^#counter-')
  return el && regex.test(el.getAttribute('href'));
}

function isMechTemplate(el) {
  return el && el.getAttribute('class') === 'mech-template';
}

function isClone(counter) {
  const isClone = counter.classList.contains('clone'),
    { allegiance: clAl, number: clNum } = counter.dataset;

  return {
    of: function ({ dataset: { allegiance, number }}) {
      return isClone && clAl == allegiance && clNum == number;
    }
  };
}

function getCellPosition(cell) {
  const [x, y] = cell.getAttributeNS(null, 'transform').match(/-?\d+\.?\d*/g);

  return { x, y };
}

function getCell(q, r, s, t) {
  return svg.querySelector(`g[data-q="${q}"][data-r="${r}"][data-s="${s}"][data-t="${t}"]`);
}

function getCounterAtGridIndex(...coords) {
  return getCell(...coords).querySelector('.counter');
}

function getSelected() {
  return svg.querySelector(`.counter.selected[data-allegiance][data-number]`);
}

function deselect() {
  const selected = getSelected();
  placing = [];

  if (selected) {
    selected.classList.remove(soldier.getSelectedClass());
    clearSightLine();
    firingArc.clipAll(svg);
  }
}

function clearSightLine() {
  sightLine.setHexes([]);
  sightLine.clear();
  Observable.notify('distance');
}

function calcSightLineIndexes(source, target) {
  const { q: sq, r: sr, s: ss } = source.dataset;
  const { q: tq, r: tr, s: ts } = target.dataset;
  const sourceIndex = { q: +sq, r: +sr, s: +ss };
  const targetIndex = { q: +tq, r: +tr, s: +ts };

  return sightLine.calcIndexes(sourceIndex, targetIndex);
}

function getSightLineHexes(indexes) {
  const selector = indexes
    .map(({ q, r, s }) => `g[data-q="${q}"][data-r="${r}"][data-s="${s}"] use[href="#hex"]`)
    .join(', ');

  return svg.querySelectorAll(selector);
}

function calcSightLine(source, target) {
  const indexes = calcSightLineIndexes(source, target);
  const hexes = getSightLineHexes(indexes);
  sightLine.setHexes(hexes);
  Observable.notify('distance', indexes.length - 1);
}

function updateSightLine(cell) {
  calcSightLine(cell, sightLine.getLockTarget());
  sightLine.update(getCellPosition(cell));
}

function drawSightLine(sourceCell, targetCell) {
  calcSightLine(sourceCell, targetCell)
  const line = sightLine.create(getCellPosition(sourceCell), getCellPosition(targetCell));
  svg.querySelector('.gameboard').appendChild(line);
}

function moveBackOneStepInHistory(counter) {
  const trace = soldier.getTrace(svg, counter);

  counter.remove();
  counter = getCounterAtGridIndex(...counter.dataset.previous.split(','));
  counter.classList.remove('clone');
  counter.classList.add(soldier.getSelectedClass());

  if (!('previous' in counter.dataset)) {
    trace.remove();
  } else {
    const points = trace.getAttribute('points').split(' ');
    points.pop();
    trace.setAttributeNS(null, 'points', points.join(' '));
  }

  return counter;
}

function clearMoveHistory(clone, counter) {
  clone.classList.remove('clone');
  clone.classList.add(soldier.getSelectedClass());
  counter.remove();
  counter = clone;
  soldier.removeClones(svg, counter);
  soldier.getTrace(svg, counter).remove();

  return counter;
}

function deleteClone(occupant, counter, cell) {
  const index = getGridIndex(occupant),
    trace = soldier.getTrace(svg, counter),
    pos = getCellPosition(cell),
    points = trace.getAttribute('points').split(' ').filter(p => p != `${pos.x},${pos.y}`).join(' ');;

  let current = counter;
  trace.setAttributeNS(null, 'points', points);

  while (current.dataset.previous != `${index.q},${index.r},${index.s},${index.t}`) {
    current = getCounterAtGridIndex(...current.dataset.previous.split(','));
  }

  current.dataset.previous = occupant.dataset.previous;
  occupant.remove();
}

function hasPreviousMoveInHistory(counter) {
  return 'previous' in counter.dataset;
}

function selectOffBoard() {
  Observable.notify('select', this);
}

function select(data) {
  const counter = data && (soldier.getCounter(svg, data) || soldier.createCounter(data));
  const isSelected = data && data.classList && data.classList.contains('selected');

  deselect();

  if (isSelected || !data) return;

  counter.classList.add(soldier.getSelectedClass());
  firingArc.get(svg, counter).forEach(el => el.removeAttribute('clip-path'));
  placing.push(counter);
}

function endMove() {
  const selected = getSelected();

  if (selected) {
    soldier.endMove(svg, selected);
    deselect();
  }
}

// Work around webkit bug https://bugs.webkit.org/show_bug.cgi?id=233432
function workaroundForWebKitBug233432(listener) {
  return e => {
    const elUnderCursor = svg.parentNode.elementFromPoint(e.clientX, e.clientY);
    if (!e.target.contains(elUnderCursor)) listener(e);
  };
}

export function start(el) {
  svg = el;
  const gridTop = svg.querySelector('.grid-top');
  top.container = svg.querySelector('.grid-top > .container');
  const topHex = svg.querySelector('.grid-top > use[href="#hex"]');

  const clearHexDialog = document.querySelector('#clear-hex');
  clearHexDialog.addEventListener('close', e => {
    if (clearHexDialog.returnValue === 'confirm') {
      [...top.container.children].forEach(child => {
        top.collection.delete(child);
        child.remove();
      });
    }
  });

  clearHexDialog.querySelector('button[value="confirm"]').addEventListener('click', function(e) {
    e.preventDefault();
    clearHexDialog.close(this.value);
  });

  gridTop.addEventListener('pointerleave', workaroundForWebKitBug233432(e => {
    [...top.container.children].forEach(child => {
      top.collection.get(child).parent.append(child);
      top.collection.delete(child);
    });

    top.cell = null;
  }));

  topHex.addEventListener('click', clickHandler);

  topHex.addEventListener('contextmenu', e => {
    e.preventDefault();
    getSelected() ? sightLine.toggleLock(top.cell) : clearHexDialog.showModal();
  });

  const startingLocations = svg.querySelector('.start-locations');
  startingLocations && getUnits(startingLocations).forEach(unit => unit.addEventListener('click', selectOffBoard));

  function clickHandler(e) {
    const occupant = svg.querySelector('.grid-top .container .counter')
    let toPlace = placing.pop();

    if (isCounter(toPlace) || isMechTemplate(toPlace)) {
      top.collection.set(toPlace, { parent: top.cell });
      top.container.append(toPlace);
      if (isCounter(toPlace)) arrangeCounters(top.container);
      removeEventListener("keydown", handleMechTemplateRotation);
    } else if (toPlace && !occupant) {
      top.collection.set(toPlace, { parent: top.cell });
      top.container.prepend(toPlace);
      placing.push(toPlace);
      getLockedSightLine(svg) ? updateSightLine(top.cell) : clearSightLine();
    } else if (toPlace && occupant) {
      if (toPlace === occupant) {
        Observable.notify('select');
      } else {
        Observable.notify('select', occupant);
      }
    } else if (!toPlace && occupant) {
      Observable.notify('select', occupant);
    }

    const selected = getSelected();
  }

  getCells(svg).forEach(cell => {
    cell.addEventListener('pointerover', () => {
      //console.log(['pointerenter', cell]);

      top.cell = cell;

      [...top.container.children].forEach(child => {
        top.collection.get(child).parent.append(child);
        top.collection.delete(child);
      });

      top.container.parentElement.setAttributeNS(null, 'transform', cell.getAttributeNS(null, 'transform'));

      [...cell.children].filter(c => c.getAttributeNS(null, 'href') !== '#hex').forEach(child => {
        top.collection.set(child, { parent: cell });
        top.container.append(child);
      });

      let occupant = svg.querySelector('.grid-top .container .counter');
      const selected = getSelected();

      if (placing[0]?.getAttributeNS(null, 'class') == 'mech-template') {
        cell.appendChild(placing[0]);
      }

      if (selected && svg.querySelector('.grid').contains(selected) && !getLockedSightLine(svg) && cell !== selected.parentElement) {
        clearSightLine();
        drawSightLine(selected.parentElement, cell);
      }

      occupant = getCellOccupant(cell);

      if (occupant) {
        firingArc.toggleCounterVisibility(svg, occupant, true);
      }
    });
  });

  //const cell = document.querySelector('[data-q="0"][data-r="0"][data-s="0"][data-t="0"]');
  //const povr = new PointerEvent('pointerover');
  //const pout = new PointerEvent('pointerout');
  //cell.dispatchEvent(povr);
  //cell.dispatchEvent(pout);

  // debug //
  // Add a trooper counter
  //const attacker = { dataset: { allegiance: 'attacker', number: 1, squad: 1 }};
  // const defender = { dataset: { allegiance: 'defender', number: 1, squad: 2 }};
  //const cell = getCell(0, 0, 0, 0);
  //const trooper = soldier.createCounter(attacker, 'blazer');
  //const trooperSack = document.createElementNS(svgns, 'g');
  //trooperSack.classList.add('cell-contents');
  //trooperSack.append(trooper);
  //soldier.place(svg, trooper, cell);

  // Add some counters in an unoccupied cell
  //const countersCell = getCell(-1, 1, 0, 0);
  //setCounter('grenade');
  //setCounter('prone');
  //setCounter('1st-floor');
  //const e = new PointerEvent('click');
  //countersCell.dispatchEvent(e);
  //countersCell.dispatchEvent(e);
  //countersCell.dispatchEvent(e);
  ///////////

  Observable.subscribe('select', select);
  Observable.subscribe('endmove', endMove);

  console.log('gameboard.js loaded');
}

export function stop() {
  Observable.unsubscribe('select', select);
  Observable.unsubscribe('endmove', endMove);
}

export function getUnits() {
  return soldier.getAllCounters(svg);
}

export function clearFiringArcs(allegiance) {
  firingArc.clear(svg, allegiance);
}

export function toggleFiringArcVisibility() {
  firingArc.toggleVisibility(svg, this.dataset.allegiance);
}

export function setFiringArc() {
  const counter = getSelected(),
    isOnBoard = counter => counter && counter.parentElement.hasAttribute('data-q');

  if (isOnBoard(counter)) {
    returnToParent(top);
    firingArc.set(svg, this.dataset.size, counter, getCellPosition(counter.parentElement));
  }
}

export function setCounter(name) {
  const selected = getSelected();
  const counter = document.createElementNS(svgns, 'use');

  counter.addEventListener('click', e => {
    e.stopPropagation()
    const container = counter.parentElement;
    counter.remove()
    arrangeCounters(container);
  });

  counter.setAttributeNS(null, 'href', `#counter-${name}`);
  counter.classList.add(`counter-${name}`);

  if (selected) {
    selected.append(counter);
    arrangeCounters(selected);
  }
  else
    placing.push(counter);
}

function arrangeCounters(container) {
  const counters = [...container.children].filter(isCounter);
  const length = 12;
  const gravity = 1;
  const lateralForce = gravity;
  const rads = Math.atan(lateralForce / gravity);
  const bestFitCount = 8;
  const deflection = counters.length > bestFitCount ? 2 * Math.PI / counters.length : Math.atan(lateralForce / gravity);

  counters.forEach((counter, index, arr) => {
    const mult = index - arr.length / 2 + 0.5;
    const theta = deflection * mult;
    const x = length * Math.sin(theta);
    const y = length * Math.cos(theta);
    counter.setAttributeNS(null, 'style', `--x: ${-x}px; --y: ${y}px`);
  });
}

function handleMechTemplateRotation(event) {
  const counter = placing[0];
  const upper = placing[0].querySelector('use[href="#mech-template-upper"]');

  if (event.key === 'a') {
    let direction = +counter.style.transform.match(/-?\d+/) || 0;
    direction -= 60;
    counter.style.transform = `rotate(${direction}deg)`;
  } else if (event.key === 'd') {
    let direction = +counter.style.transform.match(/-?\d+/) || 0;
    direction += 60;
    counter.style.transform = `rotate(${direction}deg)`;
  } else if (event.key === 'q') {
    let facing = +upper.style.transform.match(/-?\d+/) || 0;
    facing = facing <= -60 ? -60 : facing - 60;
    upper.style.transform = `rotate(${facing}deg)`;
  } else if (event.key === 'e') {
    let facing = +upper.style.transform.match(/-?\d+/) || 0;
    facing = facing >= 60 ? 60 : facing + 60;
    upper.style.transform = `rotate(${facing}deg)`;
  }
}

export function setMechTemplate() {
  const counter = document.createElementNS(svgns, 'g');
  counter.setAttributeNS(null, 'class', 'mech-template');
  counter.style.pointerEvents = 'none';
  counter.style.transition = 'transform 0.5s';

  const lower = document.createElementNS(svgns, 'use');
  lower.setAttributeNS(null, 'href', '#mech-template-lower');

  const upper = document.createElementNS(svgns, 'use');
  upper.setAttributeNS(null, 'href', '#mech-template-upper');
  upper.style.transition = 'transform 0.5s';

  counter.appendChild(lower);
  counter.appendChild(upper);

  addEventListener("keydown", handleMechTemplateRotation);
  placing.push(counter);
}
