/**
 *
 */

import { SettingsContextMenu } from '@vizality/components/vizality';
import { getModule, contextMenu } from '@vizality/webpack';
import { forceUpdateElement } from '@vizality/util/react';
import { patch, unpatch } from '@vizality/patcher';
import { Builtin } from '@vizality/entities';
import { Icon } from '@vizality/components';
import React from 'react';

import Routes from './routes/Routes';

const { openContextMenu } = contextMenu;

export default class Dashboard extends Builtin {
  /**
   * Builtin startup sequence
   * @returns {Promise<void>}
   */
  async start () {
    this.injectStyles('styles/main.scss');
    this._injectPrivateTab();
    // this.injectGuildHomeButton();

    vizality.api.routes.registerRoute({
      id: 'dashboard',
      path: '',
      render: Routes
    });

    vizality.api.actions.registerAction('VIZALITY_CLOSE_DASHBOARD', this._leaveDashboard.bind(this));
    vizality.api.actions.registerAction('VIZALITY_TOGGLE_DASHBOARD', this._toggleDashboard.bind(this));

    vizality.api.keybinds.registerKeybind({
      id: 'VIZALITY_CLOSE_DASHBOARD',
      shortcut: 'esc',
      executor: this._leaveDashboard.bind(this)
    });

    vizality.api.keybinds.registerKeybind({
      id: 'VIZALITY_TOGGLE_DASHBOARD',
      shortcut: 'alt+v',
      executor: this._toggleDashboard.bind(this)
    });
  }

  /**
   * Builtin shutdown sequence
   * @returns {Promise<void>}
   */
  async stop () {
    vizality.api.routes.unregisterRoute('dashboard');
    vizality.api.actions.unregisterAction('VIZALITY_CLOSE_DASHBOARD');
    vizality.api.actions.unregisterAction('VIZALITY_TOGGLE_DASHBOARD');
    vizality.api.keybinds.unregisterKeybind('VIZALITY_CLOSE_DASHBOARD');
    vizality.api.keybinds.unregisterKeybind('VIZALITY_TOGGLE_DASHBOARD');
    unpatch('vz-dashboard-private-channels-list-item');
  }

  /**
   * Goes to the previous non-Vizality dashboard route.
   * @returns {void}
   */
  _leaveDashboard () {
    try {
      return vizality.api.routes.restorePreviousRoute();
    } catch (err) {
      return this.error(this._labels.concat('_leaveDashboard'), err);
    }
  }

  /**
   * Opens the dashboard if the current route is not a Vizality dashboard route,
   * otherwise goes to the previous non-Vizality dashboard route.
   * @returns {void}
   */
  _toggleDashboard () {
    try {
      const currentRoute = vizality.api.routes.getLocation();
      if (currentRoute?.pathname?.startsWith('/vizality')) {
        return this._leaveDashboard();
      }
      return vizality.api.routes.navigateTo('dashboard');
    } catch (err) {
      return this.error(this._labels.concat('_toggleDashboard'), err);
    }
  }

  /**
   * Patches the private channels list to add a button just above the Friends button
   * that takes you to the Vizality dashboard.
   * @returns {void}
   */
  _injectPrivateTab () {
    try {
      const ConnectedPrivateChannelsList = getModule(m => m.default?.displayName === 'ConnectedPrivateChannelsList');
      const { channel } = getModule('channel', 'closeIcon');
      const { LinkButton } = getModule('LinkButton');
      patch('vz-dashboard-private-channels-list-item', ConnectedPrivateChannelsList, 'default', (_, res) => {
        try {
          if (!res.props?.children?.props?.children) {
            return;
          }

          res.props.children.props.children = [
            ...res.props.children.props.children.slice(0, 0),
            <LinkButton
              icon={() => <Icon name='vizality' />}
              route='/vizality'
              text='Dashboard'
              selected={vizality.api.routes.getLocation()?.pathname?.startsWith('/vizality')}
              onContextMenu={evt => openContextMenu(evt, () => <SettingsContextMenu />)}
            />,
            ...res.props.children.props.children.slice(0)
          ];
        } catch (err) {
          return this.error(this._labels.concat('_injectPrivateTab'), err);
        }
      });
      setImmediate(() => forceUpdateElement(`.${channel}`, true));
    } catch (err) {
      return this.error(this._labels.concat('_injectPrivateTab'), err);
    }
  }

  /*
   * async injectGuildHomeButton () {
   *   const guildClasses = getModule('tutorialContainer');
   *   const guildElement = (await waitForElement(`.${guildClasses.tutorialContainer.split(' ')[0]}`)).parentElement;
   *   const instance = getOwnerInstance(guildElement);
   */

  /*
   *   patch('vz-dashboard-guilds-button', instance, 'render', (_, res) => {
   *     const ogRef = res.ref;
   *     const ogChildren = res.props.children;
   */

  /*
   *     res.props.children = elem => {
   *       const r = ogChildren(elem);
   *       console.log(elem);
   *       const tee = [ elem.ref.current.children[1].children[1] ];
   *       tee.splice(1, 0, <div class='pie'>Hi lol</div>);
   *       return r;
   *     };
   *     // res.props.children[1].props.children.splice(1, 0, <div class='pie' />);
   */

  //     // pie.splice(1, 0, <div class='pie' />);

  /*
   *     return res;
   *   });
   * }
   */
}
