'use strict';

const electron = require('electron');
const ipcRenderer = electron.ipcRenderer;

const updateWindowContainer = document.getElementById(
  'update-window-container'
);

const confirmation = document.getElementById('confirmation');
const downloading = document.getElementById('downloading');
const update = document.getElementById('update');

const confirmationOk = document.getElementById('confirmation-ok');
const confirmationCancel = document.getElementById('confirmation-cancel');

const downloadingProgressBar = document.getElementById(
  'downloading-progress-bar'
);
const downloadingProgressLabel = document.getElementById(
  'downloading-progress-label'
);
const downloadingCancel = document.getElementById('downloading-cancel');

confirmationOk &&
  confirmationOk.addEventListener('click', e => {
    console.log('UCAP::ElectronUpdateWindow::acceptUpdate');
    ipcRenderer.send('UCAP::ElectronUpdateWindow::acceptUpdate');
    downloadingProgressBar.style.width = `0%`;
    downloadingProgressLabel.innerText = `0%`;
    updateWindowContainer.style.transform = 'translateX(-500px)';
  });

confirmationCancel &&
  confirmationCancel.addEventListener('click', e => {
    ipcRenderer.send('UCAP::ElectronUpdateWindow::denyUpdate');
  });

downloadingCancel &&
  downloadingCancel.addEventListener('click', e => {
    ipcRenderer.send('UCAP::ElectronUpdateWindow::cancelDownload');
  });

function setContents(event, versionInfo) {
  const updateDoc = global.window.document;

  const latestVersion = updateDoc.getElementById('latestVersion');
  if (!!latestVersion) {
    latestVersion.innerHTML = versionInfo.latest || '';
  }

  const installedVersion = updateDoc.getElementById('installedVersion');
  if (!!installedVersion) {
    installedVersion.innerHTML = versionInfo.installed || '';
  }
}

ipcRenderer.on(
  'UCAP::ElectronUpdateWindow::downloadProcess',
  (event, ...args) => {
    const percentage = (args[0] / args[1]) * 100;
    downloadingProgressBar.style.width = `${percentage}%`;
    downloadingProgressLabel.innerText = `${percentage}%`;
  }
);

ipcRenderer.on(
  'UCAP::ElectronUpdateWindow::downloadComplete',
  (event, ...args) => {
    updateWindowContainer.style.transform = 'translateX(-1000px)';
  }
);

ipcRenderer.on(
  'UCAP::ElectronUpdateWindow::BrowserWindowSetContents',
  setContents
);
