import { ChangeDetectionStrategy, Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Params } from '@msfa-models/api/params.model';
import { DeltagareAvrop } from '@msfa-models/avrop.model';
import { PeriodiskRedovisning, PeriodiskRedovisningActivity } from '@msfa-models/periodisk-redovisning.model';
import { capitalizeWords } from '@msfa-shared/utils/capitalize-words.util';
import { formatDate, formatToDate } from '@msfa-shared/utils/format-to-date.util';
import { Observable } from 'rxjs';
import { map, shareReplay, switchMap } from 'rxjs/operators';
import { PeriodiskRedovisningViewService } from './periodisk-redovisning-view.service';

@Component({
  selector: 'msfa-periodisk-redovisning-view',
  templateUrl: './periodisk-redovisning-view.component.html',
  styleUrls: ['./periodisk-redovisning-view.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PeriodiskRedovisningViewComponent {
  params$: Observable<Params> = this.activatedRoute.params.pipe(
    map(params => ({
      handlingId: params.handlingId as string,
      genomforandeReferens: params.genomforandeReferens as string,
    }))
  );
  avrop$: Observable<DeltagareAvrop> = this.params$.pipe(
    switchMap(({ genomforandeReferens }) =>
      this.periodiskRedovisningViewService.fetchAvropInformation$(+genomforandeReferens)
    ),
    shareReplay(1)
  );

  periodiskRedovisning$: Observable<PeriodiskRedovisning> = this.params$.pipe(
    switchMap(({ handlingId }) =>
      this.periodiskRedovisningViewService.fetchPeriodiskRedovisning$(handlingId as string)
    ),
    shareReplay(1)
  );

  getPeriodName(period: string): string {
    const date = formatToDate(period);
    return capitalizeWords(formatDate(date, 'sv-SE', { month: 'long', year: 'numeric' }));
  }

  getActivityInfoAsString(activity: PeriodiskRedovisningActivity): string {
    const hours = activity.hours ? (activity.hours === 1 ? '1 timme ' : `${activity.hours} timmar `) : '';
    const location =
      activity.performedRemotely && activity.performedPhysically
        ? 'på distans och på plats'
        : activity.performedRemotely
        ? 'på distans'
        : 'på plats';
    return `${activity.name}: ${hours}${location}`;
  }

  constructor(
    private periodiskRedovisningViewService: PeriodiskRedovisningViewService,
    private activatedRoute: ActivatedRoute
  ) {}
}
