import fs from 'fs';
import Canvas, { Image } from 'canvas';

import {
  isolateDistrict,
  expand,
  contract,
  contiguousRegions,
  findEdges,
  getCoords,
} from './';
import hexToRgb from '../utils/hexToRGB';


const getImageData = (src, hex) => new Promise((resolve, reject) => {
  const vCan = new Canvas(200, 200),
        vCtx = vCan.getContext('2d'),
        dMap = new Image; // eslint-disable-line new-parens

  fs.readFile(src, (err, buff) => {
    if (err) reject(err);

    dMap.src = buff;
    vCan.width = 800;
    vCan.height = 800 * (dMap.height / dMap.width);
    vCtx.drawImage(dMap, 0, 0, vCan.width, vCan.height);

    console.log(`______________${hex}___________________`);

    const imgData = vCtx.getImageData(0, 0, vCan.width, vCan.height),
          data = imgData.data,
          color = hexToRgb(hex),
          coods = [];

    isolateDistrict(data, color);
    expand(imgData, color, 10);
    contract(imgData, color, 10);

    contiguousRegions(imgData, color).forEach((region) => {
      findEdges(region, color);
      coods.push(getCoords(region, color));
    });

    resolve(coods);
  });
});

export {
  getImageData,
};
