import { promises, existsSync, closeSync, openSync } from 'fs';
import { join } from 'path';
import React from 'react';

import { Builtin } from '@vizality/entities';

import QuickCodePage from './components/QuickCode';

const { writeFile, readFile } = promises;

export default class QuickCode extends Builtin {
  async start () {
    vizality.api.settings._registerBuiltinSection({
      header: 'Quick Code',
      description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin ornare tellus nec dapibus finibus. Nulla massa velit, mattis non eros a, interdum tristique massa. Curabitur mauris sem, porttitor quis ligula vitae, suscipit hendrerit quam. Nunc sit amet enim id elit vehicula tempus sed sed tellus. Aliquam felis turpis, malesuada ut tortor id, iaculis facilisis felis.',
      icon: 'compose',
      render: props => <QuickCodePage builtin={this} {...props} />
    });

    this.watcher = false;
    this._customCSS = this.settings.get('customCSS');

    closeSync(
      openSync(join(__dirname, 'stores', 'css', 'custom.scss'), 'a')
    );

    this._customCSSFilePath = join(__dirname, 'stores', 'css', 'custom.scss');
    await this._loadCustomCSS();

    this.injectStyles('styles/main.css');
    this.injectStyles(this._customCSSFilePath, true);
  }

  stop () {
    vizality.api.routes.unregisterRoute('quick-code');
  }

  async _openCustomCSS () {
    try {
      vizality.api.popups.openPopup({
        popupId: 'VIZALITY_CUSTOM_CSS',
        title: 'Quick Code - CSS',
        titlebarType: 'WINDOWS',
        render: props => <QuickCodePage builtin={this} popout={true} {...props} />
      });
    } catch (err) {
      this.error(err);
    }
  }

  async _loadCustomCSS () {
    let customCSS = this.settings.get('customCSS');
    if (this._customCSSFilePath && existsSync(this._customCSSFilePath)) {
      customCSS = await readFile(this._customCSSFilePath, 'utf8');
    } else {
      customCSS = customCSS?.trim();
      await writeFile(join(__dirname, 'stores', 'css', 'custom.scss'), customCSS);
      this._customCSSFilePath = join(__dirname, 'stores', 'css', 'custom.scss');
    }
  }
}
