import { RouterEvent } from 'aurelia-router';
import moment from 'moment';
import { autoinject, BindingEngine, Disposable } from "aurelia-framework";
import { customElement } from "aurelia-templating";
import { AuthService } from "../../security/auth-service";
import { HttpClient } from 'aurelia-fetch-client';
import { Notification } from "../../model/common-model";
import { DialogController } from "aurelia-dialog";
import { EventAggregator } from 'aurelia-event-aggregator';
import { Utils } from './../../utils/utils';

@customElement('ui-notification-list')
@autoinject
export class UINotificationList {
  private showRead: boolean = false;

  private notificationsList: Array<Notification>;
  private notificationToShow: Notification;
  private showNotificationDetail: boolean = false;

  private showReadObserver: Disposable;

  constructor(public eventAggregator: EventAggregator, private httpClient: HttpClient, private authService: AuthService, private dialogController: DialogController, private bindingEngine: BindingEngine) {
    this.notificationsList = [];
  }

  async bind() {
    await this.loadData();
    this.showReadObserver = this.bindingEngine.propertyObserver(this, "showRead").subscribe(() => {
      //this.lastPage = 1;
      this.notificationsList?.splice(0);
      this.loadData();
    });
  }

  public async loadData() {
    let result = await this.httpClient.get(`/api/communication/${this.authService.currentUser.id}/notifications?unread=${this.showRead === true ? 'false' : 'true'}`);
    if (result.ok) {
      let notifications = await result.json();
      this.notificationsList.push(...notifications);
    }
  }

  public async setAllNotificationsRead(reloadData: boolean) {
    let unreadNotificationsList = this.notificationsList.filter(x => x.diplayedDateTime == null);
    if (unreadNotificationsList.length > 0) {
      await this.setNotificationsRead(reloadData, ...unreadNotificationsList);
    }
  }

  public async setNotificationsRead(reloadData: boolean, ...notifications: Notification[]) {
    await this.httpClient.post("/api/communication/setNotificationsRead?isDisplayed=" + true, JSON.stringify(notifications.map(x => x.id)));
    if (reloadData) {
      this.notificationsList.splice(0);
      await this.loadData();
    }
  }

  attached() {
    this.eventAggregator.subscribe(RouterEvent.Processing, () => {
      this.dialogController.close(true);
    });
  }

  detached() {
    this.showReadObserver.dispose();
  }

  private async openNotificationDetail(notification: Notification) {
    this.notificationToShow = notification;
    this.showNotificationDetail = true;
  }

  private async closeDetail() {
    this.showNotificationDetail = false;
  }

  public formatText(notification: Notification) {
    return Utils.innerHTMLFromHTML(notification?.notificationContentHTML);
  }

  public getLocalTime(dateString: string, format: string) {
    return moment.utc(dateString).local().format(format).toString();
  }
}