import { ChangeDetectionStrategy, Component, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { UnsubscribeDirective } from '@msfa-directives/unsubscribe.directive';
import { Feature } from '@msfa-enums/feature.enum';
import { RoleEnum } from '@msfa-enums/role.enum';
import { environment } from '@msfa-environment';
import { ContactInformation } from '@msfa-models/contact-information.model';
import { Role } from '@msfa-models/role.model';
import { UserService } from '@msfa-services/user.service';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { DeltagareCardService } from './deltagare-card.service';

@Component({
  selector: 'msfa-deltagare-details',
  templateUrl: './deltagare-card.component.html',
  styleUrls: ['./deltagare-card.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DeltagareCardComponent extends UnsubscribeDirective implements OnDestroy {
  activeTab$: Observable<string> = this.deltagareCardService.activeTab$;
  genomforandereferens$: Observable<number> = this.activatedRoute.params.pipe(
    map(({ genomforandeReferens }) => +genomforandeReferens)
  );

  private _activeFeatures: Feature[] = environment.activeFeatures;
  private _userRoles$: Observable<Role[]> = this.userService.userRoles$;

  deltagareTjanstVisible$: Observable<boolean> = this._userRoles$.pipe(
    map(roles =>
      roles.some(role => role.type === RoleEnum.MSFA_ReportAndPlanning || role.type === RoleEnum.MSFA_ReceiveDeltagare)
    )
  );
  handledarePickerVisible$: Observable<boolean> = this._userRoles$.pipe(
    map(roles => roles.some(role => role.type === RoleEnum.MSFA_ReceiveDeltagare))
  );
  reportingTabVisible$: Observable<boolean> = this._userRoles$.pipe(
    map(
      roles =>
        roles.some(role => role.type === RoleEnum.MSFA_ReportAndPlanning) &&
        this._activeFeatures.includes(Feature.REPORTING)
    )
  );
  experiencesVisible$: Observable<boolean> = this._userRoles$.pipe(
    map(roles => roles.some(role => role.type === RoleEnum.MSFA_ReportAndPlanning))
  );
  sensitiveDataVisible$: Observable<boolean> = this._userRoles$.pipe(
    map(
      roles =>
        roles.some(role => role.type === RoleEnum.MSFA_ReportAndPlanning) &&
        this._activeFeatures.includes(Feature.DELTAGARE_SENSITIVE_INFORMATION)
    )
  );

  contactInformation$: Observable<ContactInformation> = this.deltagareCardService.contactInformation$;

  constructor(
    private activatedRoute: ActivatedRoute,
    private deltagareCardService: DeltagareCardService,
    private userService: UserService
  ) {
    super();
    super.unsubscribeOnDestroy(
      this.activatedRoute.params.subscribe(params => {
        this.deltagareCardService.setGenomforandereferens(params.genomforandeReferens as string);
      })
    );
  }

  setActiveTab(tabId: string): void {
    this.deltagareCardService.setActiveTab(tabId);
  }
}
