/*
 * 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 {Component, ContentChild, Input, OnDestroy, OnInit, TemplateRef} from '@angular/core';
import opening_hours from 'opening_hours';

@Component({
  selector: 'stapps-opening-hours',
  templateUrl: 'opening-hours.html',
})
export class OpeningHoursComponent implements OnDestroy, OnInit {
  @ContentChild(TemplateRef) content: TemplateRef<unknown>;

  @Input() openingHours?: string;

  @Input() colorize = true;

  @Input() showNextChange = true;

  timer: NodeJS.Timeout;

  updateTimer() {
    if (typeof this.openingHours !== 'string') {
      return;
    }
    clearTimeout(this.timer);

    const ohObject = new opening_hours(this.openingHours, {
      address: {
        country_code: 'de',
        state: 'Hessen',
      },
      lon: 8.667_97,
      lat: 50.129_16,
    });

    const millisecondsRemaining =
      // eslint-disable-next-line unicorn/prefer-date-now
      (ohObject.getNextChange()?.getTime() ?? 0) - new Date().getTime() + 1000;

    if (millisecondsRemaining > 1_209_600_000) {
      // setTimeout has upper bound of 0x7FFFFFFF
      // ignore everything over a week
      return;
    }

    if (millisecondsRemaining > 0) {
      this.timer = setTimeout(() => {
        // pseudo update value to tigger openingHours pipe
        this.openingHours = `${this.openingHours}`;
        this.updateTimer();
      }, millisecondsRemaining);
    }
  }

  ngOnInit() {
    this.updateTimer();
  }

  ngOnDestroy() {
    clearTimeout(this.timer);
  }
}
