import { TreeNode } from 'src/types/stores/kanvaso';

export default class ObjectWrapper {
  private _wrappingObject: TreeNode;

  constructor(wrappingObject: TreeNode) {
    this._wrappingObject = wrappingObject;
    this._wrappingObject.childrens = this._wrappingObject.childrens || [];
  }

  private _getSafeProperty = <T>(propertyPath: () => T, defaultValue: T): T => {
    try {
      const value = propertyPath();
      return value !== undefined ? value : defaultValue;
    } catch {
      return defaultValue;
    }
  };

  get name(): string {
    return this._getSafeProperty(
      () => this._wrappingObject.nomo.enhavo,
      'Без имени',
    );
  }

  get isPublished(): boolean {
    return this._getSafeProperty(() => this._wrappingObject.publikigo, true);
  }

  get isDeleted(): boolean {
    return this._getSafeProperty(() => this._wrappingObject.forigo, false);
  }

  get description(): string {
    return this._getSafeProperty(
      () => this._wrappingObject.priskribo.enhavo,
      'Нет описания',
    );
  }

  get id(): number {
    return this._getSafeProperty(() => this._wrappingObject.objId, 0);
  }

  get uuid(): string {
    return this._getSafeProperty(() => this._wrappingObject.uuid, null);
  }

  get type(): string {
    return this._getSafeProperty(
      () => this._wrappingObject.tipo.nomo.enhavo,
      'Без типа',
    );
  }

  get typeId(): number {
    return this._getSafeProperty(() => this._wrappingObject.tipo.objId, 0);
  }

  get parentUuid(): string {
    return this._getSafeProperty(
      () =>
        this._wrappingObject.kanvasojKanvasoobjektoligiloLigilo.posedanto.uuid,
      '',
    );
  }

  get childrens(): ObjectWrapper[] {
    return this._wrappingObject.childrens;
  }

  setChildrens(childrens: ObjectWrapper | ObjectWrapper[]): void {
    if (Array.isArray(childrens)) {
      this._wrappingObject.childrens.push(...childrens);
    } else {
      this._wrappingObject.childrens.push(childrens);
    }
  }

  removeChildrens() {
    this._wrappingObject.childrens.length = 0;
  }

  get hasParent(): boolean {
    return !!this._wrappingObject.kanvasojKanvasoobjektoligiloLigilo;
  }
}
