const { desktopCapturer, remote } = require('electron');
const ratio = window.devicePixelRatio;
const Vibrant = require('../vibrant.min');

desktopCapturer.getSources({ types: ['screen'] }, (error, sources) => {
  if (error) throw error;
  sources.some(source => {
    navigator.mediaDevices.getUserMedia({
      audio: false,
      video: {
        mandatory: {
          chromeMediaSource: 'desktop'
        }
      }
    }).then(stream => {
      window.stream = stream;
    }).catch((e) => {
      console.log(e);
    });
  });
});

const closeButton = document.getElementById('close-button');
closeButton.addEventListener("click", event => {
  window = remote.getCurrentWindow();
  window.close();
});

function getWindowColors(scriptName) {
  const browserWindow = remote.getCurrentWindow();
  const pos = browserWindow.getPosition();
  const x = pos[0];
  const y = pos[1];

  const size = browserWindow.getSize();
  const width = size[0];
  const height = size[1];

  const video = document.createElement('video');
  video.srcObject = window.stream;
  video.onloadedmetadata = () => {
    video.play();

    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;

    const ctx = canvas.getContext('2d');
    ctx.drawImage(video, x, y, width * ratio, height * ratio, 0, 0, width, height);

    var image = new Image();
    image.src = canvas.toDataURL();

    Vibrant.from(image).getPalette().then(palette => {
      const output = {
        colors: [
          [palette.Vibrant.r, palette.Vibrant.g, palette.Vibrant.b],
          [palette.Muted.r, palette.Muted.g, palette.Muted.b],
          [palette.LightVibrant.r, palette.LightVibrant.g, palette.LightVibrant.b],
          [palette.LightMuted.r, palette.LightMuted.g, palette.LightMuted.b],
          [palette.DarkVibrant.r, palette.DarkVibrant.g, palette.DarkVibrant.b],
          [palette.DarkMuted.r, palette.DarkMuted.g, palette.DarkMuted.b],
        ]
      };

      window[`gml_Script_${scriptName}`](null, null, JSON.stringify(output));
    });
  }
}

function init(id) {
  window.c = document.getElementById(id).getContext('2d');
}

function ex() {
  window.c.clearRect(0, 0, c.width, c.height);
}

function ready() {
  remote.getCurrentWindow().show();
}
