import * as plugins from '../plugins.js';
import { domtools } from '@design.estate/dees-element'

export class IdpState {
  // STATIC
  private static idpStateDeferred = plugins.smartpromise.defer<IdpState>();
  public static async getSingletonInstance() {
    if (!this.idpStateDeferred.claimed) {
      this.idpStateDeferred.claim();
      const newIdpState = new IdpState();
      await newIdpState.init();
      this.idpStateDeferred.resolve(newIdpState);
    }
    return this.idpStateDeferred.promise;
  }

  // INSTANCE
  public receptionUrl = window.location.origin;
  public idpClient = new plugins.idpClient.IdpClient(this.receptionUrl);
  public domtools: domtools.DomTools;
  public mainStatePart: plugins.deesDomtools.plugins.smartstate.StatePart<'main', {
    view: 'welcome' | 'login' | 'register' | 'finishregistration' | 'account' | 'logout';
  }>

  public async init() {
    this.idpClient.enableTypedSocket();
    const domtoolsInstance = await domtools.DomTools.setupDomTools();
    this.domtools = domtoolsInstance;
    const state = new plugins.deesDomtools.plugins.smartstate.Smartstate<'main'>();
    this.mainStatePart = await state.getStatePart('main', {
      view: 'welcome',
    }, 'soft');
    this.domtools.router.on('/', async () => {
      await this.mainStatePart.setState({
        ...this.mainStatePart.getState(),
        view: 'welcome',
      })
    });

    this.domtools.router.on('/login', async () => {
      await this.mainStatePart.setState({
        ...this.mainStatePart.getState(),
        view: 'login',
      })
    });

    this.domtools.router.on('/logout', async () => {
      await this.idpClient.logout();
      await this.mainStatePart.setState({
        ...this.mainStatePart.getState(),
        view: 'logout',
      })
    });

    this.domtools.router.on('/register', async () => {
      await this.mainStatePart.setState({
        ...this.mainStatePart.getState(),
        view: 'register',
      })
    });

    this.domtools.router.on('/finishregistration', async () => {
      await this.mainStatePart.setState({
        ...this.mainStatePart.getState(),
        view: 'finishregistration',
      })
    });

    this.domtools.router.on('/account{/*path}', async () => {
      await this.mainStatePart.setState({
        ...this.mainStatePart.getState(),
        view: 'account',
      })
    });

    this.domtools.router._handleRouteState();
  }
}