import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { UnsubscribeDirective } from '@msfa-directives/unsubscribe.directive';
import { Organization } from '@msfa-models/organization.model';
import { UserService } from '@msfa-services/api/user.service';
import { Observable } from 'rxjs';
import { filter } from 'rxjs/operators';

@Component({
  selector: 'msfa-organization-picker',
  templateUrl: './organization-picker.component.html',
  styleUrls: ['./organization-picker.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class OrganizationPickerComponent extends UnsubscribeDirective {
  organizations$: Observable<Organization[]> = this.userService.organizations$.pipe(
    filter(organizations => !!organizations?.length)
  );

  constructor(
    private userService: UserService,
    private router: Router,
    private titleService: Title,
    private activatedRoute: ActivatedRoute
  ) {
    super();
    super.unsubscribeOnDestroy(
      this.organizations$.subscribe(organizations => {
        if (organizations.length === 1) {
          this.loginWithOrganization(organizations[0]);
        }
      })
    );

    const pageTitle = this.activatedRoute?.snapshot?.data?.title as string;

    this.titleService.setTitle(`Mina sidor för fristående aktörer${pageTitle ? ` - ${pageTitle}` : ''}`);
  }

  loginWithOrganization(organization: Organization): void {
    this.userService.setSelectedOrganization(organization);
    void this.router.navigateByUrl('/');
  }
}
