const path = require('path');
const { imageCreate, imageWrite, imageLoad, imageCopy } = require('./../../utils/image');
const fs =require('fs');

// Where to crop
const FACE_AREA = { x: 367, y: 256, width: 280, height: 280 };

// Where the images are stored
const IMAGES_ROOT = path.join(...[
  '.', 
  'assets',
  'characters',
  'penny',
  'sprites'
]);

// Which image directories to crop
const IMAGES_DIRECTORIES = [ 'eyebrows', 'eyes', 'mouths' ];

(async () => {
  // Load the base
  const base = await imageLoad(path.join(IMAGES_ROOT, 'dealer.png'));

  let columnsMax = 0;
  for(let row = 0; row < IMAGES_DIRECTORIES.length; row++) {
    const dir = path.join(IMAGES_ROOT, IMAGES_DIRECTORIES[row]);
    const scan = fs.readdirSync(dir);
    columnsMax = Math.max(scan.length, columnsMax);
  }

  // Create the output buffer
  const out = imageCreate(base.width+(columnsMax*FACE_AREA.width), base.height);

  // Copy the base
  imageCopy(out, base, 0, 0);
  
  // Now begin copying the children, row is defined by the directory
  for(let row = 0; row < IMAGES_DIRECTORIES.length; row++) {
    const dir = path.join(IMAGES_ROOT, IMAGES_DIRECTORIES[row]);
    const scan = fs.readdirSync(dir);

    // Column defined by the file index
    for(let col = 0; col < scan.length; col++) {
      const img = await imageLoad(path.join(dir, scan[col]));
      console.log('Copying', scan[col]);

      imageCopy(out, img,
        base.width+(col*FACE_AREA.width), FACE_AREA.height*row,
        FACE_AREA
      );
    }
  }


  await imageWrite(out, path.join(IMAGES_ROOT, 'sheet.png'));
})().catch(console.error);