import { Component, OnDestroy, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { INotificationModel } from '@fleio-api/notifications/model/notification.model';
import { of, Subscription } from 'rxjs';
import { UserNotificationsApiService } from '@fleio-api/notifications/user-notifications-api.service';
import { NavigationEnd, Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { RefreshService } from '@shared/ui-api/refresh.service';

@Component({
  selector: 'app-notification-details-message',
  templateUrl: './notification-details-message.component.html',
  styleUrls: ['./notification-details-message.component.scss']
})
export class NotificationDetailsMessageComponent extends DetailsFormBase<INotificationModel>
  implements OnInit, OnDestroy {
  private routerSubscription: Subscription;

  constructor(
    private userNotificationsApiService: UserNotificationsApiService,
    private router: Router,
    private config: ConfigService,
    private refreshService: RefreshService,
  ) {
    super();
  }

  switchReadStatus() {
    let request;
    if (this.object.status === 'pending') {
      request = this.userNotificationsApiService.setViewed(this.object.id);
    } else {
      request = this.userNotificationsApiService.setUnseen(this.object.id);
    }

    request.subscribe(() => {
      this.router.navigateByUrl(
        this.config.getPrevUrl('user/notifications')
      ).catch(() => {
      });
    });
    return of(null);
  }

  ngOnDestroy() {
    if (this.routerSubscription) {
      this.routerSubscription.unsubscribe();
      this.routerSubscription = null;
    }
  }

  notificationViewed() {
    if (this.object.status !== 'seen') {
      this.userNotificationsApiService.setViewed(this.object.id).subscribe(() => {
        this.refreshService.refresh();
      });
    }
  }

  ngOnInit(): void {
    if (this.objectController) {
      this.objectController.actionCallback = () => this.switchReadStatus();
    }
    this.notificationViewed();
    this.routerSubscription = this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        // this is used for cases when navigating from a notification to another
        // (e.g. when having panel top notifications)
        this.notificationViewed();
      }
    });
  }

}
