import allMenuItemsGenerator from './menuItemsGenerator';
import axios from 'axios';
import menuActions from './menuActions';
import treeGenerator from './treeGenerator';
globalThis.berLimit = {};

type Node = { type: string; value: string };

class Jstree {
  public copyType: string;
  public copyValue: string;
  public isLicenseValid: boolean;
  public isBerLimit: [];

  public nodeActions: any;
  public menuItems: object;

  constructor() {
    this.copyType = '';
    this.copyValue = '';
  }

  private requestIsForMorePoint = async () => {
    let token = document.head.querySelector('meta[name="csrf-token"]');
    axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    axios.defaults.headers.common['X-CSRF-TOKEN'] = (token as any).content;

    try {
      const d = await axios.get('/system/license');
      const berLimit = await axios.get("/TreeBerLimit");
      globalThis.berLimit =  berLimit.data;
      return {
        isLicenseValid: d.data,
        berLimit: berLimit.data
      };

    } catch (e) {
      this.isLicenseValid = false;
    }
  };

  public getCopy = (): Node => {
    return {
      type: this.copyType,
      value: this.copyValue,
    };
  };

  public setCopy = ({ type, value }: Node) => {
    this.copyType = type;
    this.copyValue = value;
  };

  public renderTree = async () => {
    const result = await this.requestIsForMorePoint();
    this.isLicenseValid  = result.isLicenseValid;
    this.isBerLimit  = result.berLimit;
    const actions = this.getActions();
    const menuItems = this.getMenuItems(actions);
    return treeGenerator(menuItems);
  };

  private getActions = () => {
    return menuActions(this.setCopy, this.getCopy);
  };

  private getMenuItems = (actions) => {  
    return allMenuItemsGenerator(actions, this.getCopy, this.isLicenseValid, this.isBerLimit);
  };
}

const jstree = new Jstree();

jstree.renderTree().then((tree) => {
  (window as any).configJstree = tree;
});
