/*
 * Copyright (C) 2023 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {ChangeDetectionStrategy, Component, ContentChild, Input, TemplateRef} from '@angular/core';
import {interval, Observable} from 'rxjs';
import {fromOpeningHours} from './opening-hours';
import {map, startWith} from 'rxjs/operators';

@Component({
  selector: 'stapps-opening-hours',
  templateUrl: 'opening-hours.html',
  styleUrls: ['opening-hours.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class OpeningHoursComponent {
  @ContentChild(TemplateRef) content: TemplateRef<unknown>;

  @Input() colorize = true;

  @Input() showNextChange = true;

  openingHours$?: Observable<{
    color: 'light' | 'warning' | 'success' | 'danger';
    statusName: string;
    statusText?: string;
    nextChangeAction: 'closing' | 'opening';
    nextChangeSoon?: Observable<Date | undefined>;
    nextChange?: Date;
  }>;

  @Input() set openingHours(value: string | undefined) {
    if (!value) return;
    this.openingHours$ = fromOpeningHours(value).pipe(
      map(({isUnknown, isOpen, changesSoon, nextChange, comment}) => ({
        color: isUnknown ? 'light' : changesSoon ? 'warning' : isOpen ? 'success' : 'danger',
        statusName: `common.openingHours.state_${isUnknown ? 'maybe' : isOpen ? 'open' : 'closed'}`,
        statusText: comment,
        nextChangeAction: isOpen ? 'closing' : 'opening',
        nextChangeSoon: changesSoon
          ? interval(60_000).pipe(
              startWith(nextChange),
              map(() => nextChange),
            )
          : undefined,
        nextChange,
      })),
    );
  }
}
