import { world_update } from '../world/world.js';
import { lattice_rules } from './lattice_rules.js';


function apply(f, n, x0) {
  if (n == 0) {
    return x0;
  } else {
    return f(apply(f, n-1, x0));
  }
}


test("blinker", () => {
  const L = { type: 'active', flags: {} };
  const D = { type: 'empty', flags: {} };
  const lattice = [
    [ D, D, D, D, D ],
    [ D, D, D, D, D ],
    [ D, L, L, L, D ],
    [ D, D, D, D, D ],
    [ D, D, D, D, D ],
  ];

  const world = { lattice, lattice_rules, agents: [], senses: [], actions: [] };
  expect(world_update(world).lattice).toEqual([
    [ D, D, D, D, D ],
    [ D, D, L, D, D ],
    [ D, D, L, D, D ],
    [ D, D, L, D, D ],
    [ D, D, D, D, D ],
  ]);
  expect(world_update(world_update(world)).lattice).toEqual(lattice);
});


test("glider", () => {
  const L = { type: 'active', flags: {} };
  const D = { type: 'empty', flags: {} };
  const lattice = [
    [ D, D, D, D, D, D ],
    [ D, D, D, L, D, D ],
    [ D, L, D, L, D, D ],
    [ D, D, L, L, D, D ],
    [ D, D, D, D, D, D ],
    [ D, D, D, D, D, D ],
  ];

  const world = { lattice, lattice_rules, agents: [], senses: [], actions: [] };
  //expect(world_update(world).lattice).toEqual([
  expect(apply(world_update, 1, world).lattice).toEqual([
    [ D, D, D, D, D, D ],
    [ D, D, L, D, D, D ],
    [ D, D, D, L, L, D ],
    [ D, D, L, L, D, D ],
    [ D, D, D, D, D, D ],
    [ D, D, D, D, D, D ],
  ]);
  expect(apply(world_update, 2, world).lattice).toEqual([
    [ D, D, D, D, D, D ],
    [ D, D, D, L, D, D ],
    [ D, D, D, D, L, D ],
    [ D, D, L, L, L, D ],
    [ D, D, D, D, D, D ],
    [ D, D, D, D, D, D ],
  ]);
  expect(apply(world_update, 3, world).lattice).toEqual([
    [ D, D, D, D, D, D ],
    [ D, D, D, D, D, D ],
    [ D, D, L, D, L, D ],
    [ D, D, D, L, L, D ],
    [ D, D, D, L, D, D ],
    [ D, D, D, D, D, D ],
  ]);
  expect(apply(world_update, 4, world).lattice).toEqual([
    [ D, D, D, D, D, D ],
    [ D, D, D, D, D, D ],
    [ D, D, D, D, L, D ],
    [ D, D, L, D, L, D ],
    [ D, D, D, L, L, D ],
    [ D, D, D, D, D, D ],
  ]);
});


test("beehive", () => {
  const L = { type: 'active', flags: {} };
  const D = { type: 'empty', flags: {} };
  const lattice = [
    [ D, D, D, D, D, D ],
    [ D, D, L, L, D, D ],
    [ D, L, D, D, L, D ],
    [ D, D, L, L, D, D ],
    [ D, D, D, D, D, D ],
  ];

  const world = { lattice, lattice_rules, agents: [], senses: [], actions: [] };
  //expect(world_update(world).lattice).toEqual([
  expect(apply(world_update, 1, world).lattice).toEqual(lattice);
});