import { LabelMenu } from './../panels/ui-sidebar';
import { HttpClient } from 'aurelia-fetch-client';
import { bindable, BindingEngine, bindingMode, computedFrom, customElement } from "aurelia-framework";
import { UIContent } from "./ui-content";
import { UISection } from "./ui-section";
import { Config } from '../../config';
import * as breeze from 'breeze-client';
import { ChatHistoryUtils } from '../../utils/chat-history-utils';

@customElement("ui-page")
export class UIPage {
  @bindable()
  public entity: breeze.Entity & { id: number };

  @bindable()
  public showHistory: boolean = true;

  @bindable()
  public showChat: boolean = true;

  @bindable
  public labels: Array<LabelMenu> = [];

  @bindable({ defaultBindingMode: bindingMode.twoWay })
  public currentLabelSelected: LabelMenu;

  @bindable
  public sidebarWidth: string = "24rem";

  @bindable
  public sidebarCollapsed: boolean = true;

  @bindable
  public sidebarVisible: boolean = true;

  private chatMessagesCounter: number = null;

  constructor(private httpClient: HttpClient, private config: Config, public bindingEngine: BindingEngine, private utils: ChatHistoryUtils) {
    this.showHistory = this.config.globalConfig.showHistory;
    this.showChat = this.config.globalConfig.showChat;
  }

  @computedFrom('viewHistory', 'entity.id')
  public get isViewHistory(): boolean {
    return this.utils.viewHistory && this.entity?.id > 0;
  }

  @computedFrom('viewChat', 'entity.id')
  public get isViewChat(): boolean {
    return this.utils.viewChat && this.entity?.id > 0;
  }

  async bind() {
    if (this.showHistory && this.entity != null) {
      await this.refreshHistory();
    }
    if (this.showChat && this.entity != null) {
      await this.refreshChat();
    }
  }

  async entityChanged(newValue, oldValue) {
    if (newValue != oldValue && newValue?.entityType?.shortName) {
      await this.refreshHistory();
      await this.refreshChat();
    }
  }

  private async refreshHistory() {
    this.utils.viewHistory = await this.utils.canViewHistory(this.entity);
    if (this.utils.viewHistory) {
      if (this.labels.find(x => x.uniqueIdentifiant == 'history') == null) {
        this.labels.push({ name: "common:history.history", isSelected: false, uniqueIdentifiant: 'history' });
      }
    } 
    else {
      this.labels = this.labels.filter(x => x.uniqueIdentifiant != 'history');
    }

  }

  private async refreshChat() {
    this.utils.viewChat = await this.utils.canViewChat(this.entity);
    if (this.utils.viewChat) {
      if (this.labels.find(x => x.uniqueIdentifiant == 'chat') == null) {
        this.labels.push({ name: "common:chat.chat", isSelected: false, uniqueIdentifiant: 'chat' });
        if (this.config.communicationConfig.allowChatCountFetch) {
          this.getChatNbMessages().then((result: number) => {
            this.chatMessagesCounter = result;
          });
        }
      }
    } 
    else {
      this.labels = this.labels.filter(x => x.uniqueIdentifiant != 'chat');
    }
  }

  
  private async getChatNbMessages(): Promise<number> {
    if (this.entity) {
      let result = await this.httpClient.fetch(this.config.globalConfig.remoteServiceName + "/api/communication/messages/count/" + this.entity.id + "/" + this.entity.entityType.shortName);
      if (result.ok) {
        return await result.json() as number;
      }
    }
    return 0;
  }
}

export const Page = [UIPage, UISection, UIContent];