import { Component, EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ISubheaderConfig } from '@shared/ui-api/interfaces/route-config/subheader-config';
import { Subscription } from 'rxjs';
import { IObjectListController } from '../interfaces/object-list-controller';
import { AppLocalStorageService } from '@shared/ui-api/app-local-storage.service';
import { ThemingService } from '@shared/ui/theming/theming.service';
import { AuthService } from '@shared/auth/auth.service';

@Component({
  selector: 'app-objects-subheader',
  templateUrl: './objects-subheader.component.html',
  styleUrls: ['./objects-subheader.component.scss']
})
export class ObjectsSubheaderComponent implements OnInit, OnDestroy {
  @ViewChild('filteringDisplayComponent') filteringDisplayComponent;
  @Input() cardsDisplay: boolean;
  @Input() objectsListController: IObjectListController;
  @Input() listOnly = false;
  @Output() changedCardsDisplay = new EventEmitter<boolean>();
  listViewTooltip = $localize`List view`;
  cardViewTooltip = $localize`Card view`;
  subheaderBaseTopOffset = 64;
  subheaderTopOffsetStr = '64px';

  public config: ISubheaderConfig;
  private routeDataSubscription: Subscription;
  private appTopOffsetSubscription: Subscription;

  constructor(
    public activatedRoute: ActivatedRoute,
    private appLocalStorage: AppLocalStorageService,
    private themingService: ThemingService,
    private auth: AuthService,
  ) {
  }

  ngOnInit() {
    this.routeDataSubscription = this.activatedRoute.data.subscribe(
      routeData => {
        if (routeData.config && routeData.config.subheader) {
          this.config = routeData.config.subheader;
          this.config.showRegionSelector &&= !this.config.regionSelectorFeature || this.auth.feature(this.config.regionSelectorFeature);
        } else {
          this.config = null;
        }
      },
    );
    this.appTopOffsetSubscription = this.themingService.observableAppTopOffset.subscribe(value => {
      const newOffset = this.subheaderBaseTopOffset + value;
      this.subheaderTopOffsetStr = `${newOffset}px`;
    });
  }

  toggleDisplay() {
    this.cardsDisplay = !this.cardsDisplay;
    this.changedCardsDisplay.emit(this.cardsDisplay);
    this.appLocalStorage.setCardsDisplay(this.cardsDisplay);
  }

  ngOnDestroy(): void {
    if (this.routeDataSubscription) {
      this.routeDataSubscription.unsubscribe();
      this.routeDataSubscription = null;
    }
    if (this.appTopOffsetSubscription) {
      this.appTopOffsetSubscription.unsubscribe();
      this.appTopOffsetSubscription = null;
    }
  }
}
