const path = require('path');
const {
  init,
  isOpened,
  open,
  close,
  on,
  getConfig,
  setRoot,
  getDeviceConfig
} = require('../dist/index.js');

const appName = require('./package.json').name
const localConfigPath = __dirname;
const defaultConfigPath = path.join(__dirname, 'distr');
const deviceConfigPath = __dirname;
let config = null;

on('info', (message) => console.log(message));
on('warn', (message) => console.warn(message));
on('error', (message) => console.error(message));
on('open', (message) => console.log(message));
on('close', (message) => console.log(message));
on('ready', (message, object) => {
  console.log(message);

  config = object;

  console.log('local config: ', config);

  console.log('device config: ', getDeviceConfig());

  setRoot(document.body);

  const hint = document.getElementById('hint');
  hint.innerHTML =
    'Конфиг готов к запуску<br>Ctrl + Shift + C, чтобы открыть его<br/><br/>или<br/><br/>';

  const button = document.querySelector('.Example_button');
  button.style.display = 'block';
  button.addEventListener('click', () => open(document.body));

  document.addEventListener('keydown', (e) => {
    if (e.ctrlKey && e.shiftKey && e.code === 'KeyC') {
      if (isOpened()) {
        close();
      } else {
        open();
      }
    }
  });
});

on('saved', (message, object) => {
  console.log(message);

  config = object;
});

on('close', () => {
  document.getElementById('hint').innerHTML = '☻';
  document.getElementById('hint').style.fontSize = '300px';
  document.querySelector('.Example_button').removeAttribute('style');
});

on('error', (error) => {
  document.getElementById('hint').innerHTML = `Произошла ошибка:<br/>${error.replace('[config] [error] ',)}`;
});

on('saved', (message, newConfig) => console.log(message, newConfig));

init({
  appName,
  defaultConfigPath,
  localConfigPath,
  deviceConfigPath,
});