let webChimera;
if (process.arch === 'ia32') {
  webChimera = require('../src/lib/webchimera.js_x86/index.js');
} else {
  webChimera = require('../src/lib/webchimera.js_x64/index.js');
}
const webgl = require("webgl-video-renderer");

function init(width, height, lines, rows) {
  for (let index = 0; index < lines; index++) {
      let line = document.createElement('div');
      line.setAttribute('class', 'line');
      line.setAttribute('id', 'line-' + index);
      for(let j = 0; j < rows; j++) { // columns
          let row = document.createElement('div');
          let testInfo = document.createElement('div');
          testInfo.setAttribute('class', 'testInfo testInfoLine-' + index);
          testInfo.appendChild(document.createTextNode(j + 1));
          row.appendChild(testInfo);
          row.setAttribute('id', 'row-' + index + '-' + j);
          row.setAttribute('class', 'row');
          let canvas = document.createElement('canvas');
          canvas.setAttribute('id', 'vc-' + index + '-' + j);
          canvas.setAttribute('class', 'canvas');
          row.appendChild(canvas);
          line.appendChild(row);
      }
      document.getElementById('videoGrid').appendChild(line);
  }

  window.contextsArray = [];
  window.gridPlayers = [];
  window.isBusy = [];
  window.frameReady = [];

  for (let index = 0; index < lines; index++) {
      gridPlayers[index] = [];
      window.contextsArray[index] = [];
      window.isBusy[index] = [];
      window.frameReady[index] = [];
      for(let j = 0; j < rows; j++) {
          window.contextsArray[index][j] = webgl.setupCanvas(document.getElementById('vc-' + index + '-' + j));
          window.gridPlayers[index][j] = webChimera.createPlayer();
          window.gridPlayers[index][j].onFrameReady = function(frame) {
            window.frameReady[index][j] = true;
            window.contextsArray[index][j].render(frame, frame.width, frame.height, frame.uOffset, frame.vOffset);
          }
          window.isBusy[index][j] = false;
          window.frameReady[index][j] = false;
          window.gridPlayers[index][j].onStopped = function() {
            const context = window.contextsArray[index][j].canvas.getContext('webgl');
            const color = context.clearColor(0,0,0,0);
            context.clear(color);
            setTimeout(() => {
              context.clear(color);
            }, 200);
          }
          window.gridPlayers[index][j].onFrameSetup = function(width, height) {
            console.log('frame setup');
            window.frameReady[index][j] = true;
            console.log(width, height);
          }
      }
  }

  document.getElementById("videoGrid").style.background = '#333';
  setTimeout( () => {
    document.getElementById('loading').style.opacity = 0;
    setTimeout(() => {
        document.getElementById('loading').style.visibility = 'hidden';
    }, 300)
  }, 1000)
}

window.init = init;