/*
 * Copyright (C) 2019 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, Input, OnInit} from '@angular/core';
import {SCDateSeries} from '@openstapps/core';
import {ScheduleProvider, toDateSeriesRelevantData} from '../../../calendar/schedule.provider';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {DataRoutingService} from '../../data-routing.service';
import {Router} from '@angular/router';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';

@Component({
  selector: 'stapps-date-series-detail-content',
  templateUrl: 'date-series-detail-content.html',
  styleUrls: ['date-series-detail-content.scss'],
})
export class DateSeriesDetailContentComponent implements OnInit {
  @Input() item: SCDateSeries;

  isInCalendar: Observable<boolean>;

  constructor(
    readonly scheduleProvider: ScheduleProvider,
    dataRoutingService: DataRoutingService,
    router: Router,
  ) {
    dataRoutingService
      .itemSelectListener()
      .pipe(takeUntilDestroyed())
      .subscribe(item => {
        void router.navigate(['/data-detail', item.uid], {state: {item}});
      });
  }

  ngOnInit() {
    this.isInCalendar = this.scheduleProvider.uuids$.pipe(map(it => it.includes(this.item.uid)));
  }

  addToCalendar() {
    const current = this.scheduleProvider.partialEvents$.value;
    this.scheduleProvider.partialEvents$.next([...current, toDateSeriesRelevantData(this.item)]);
  }

  removeFromCalendar() {
    const filtered = this.scheduleProvider.partialEvents$.value.filter(it => it.uid !== this.item.uid);
    this.scheduleProvider.partialEvents$.next(filtered);
  }
}
