/*
 * Copyright (C) 2022 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, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {newsFilterSettingsFieldsMapping, NewsFilterSettingsNames} from '../../news-filter-settings';
import {SCSearchValueFilter, SCSetting} from '@openstapps/core';
import {DataProvider} from '../../../data/data.provider';

@Component({
  selector: 'stapps-news-settings-filter',
  templateUrl: './news-settings-filter.component.html',
  styleUrls: ['./news-settings-filter.component.scss'],
})
export class NewsSettingsFilterComponent implements OnInit {
  /**
   * A map of the filters where the keys are settings names
   */
  filtersMap = new Map<NewsFilterSettingsNames, SCSearchValueFilter>();

  /**
   * Emits the current filters
   */
  @Output() filtersChanged = new EventEmitter<SCSearchValueFilter[]>();

  /**
   * Provided settings to show the filters for
   */
  @Input() settings: SCSetting[];

  ngOnInit() {
    for (const setting of this.settings) {
      this.filtersMap.set(
        setting.name as NewsFilterSettingsNames,
        DataProvider.createValueFilter(
          newsFilterSettingsFieldsMapping[setting.name as NewsFilterSettingsNames],
          setting.value as string,
        ),
      );
    }

    this.filtersChanged.emit([...this.filtersMap.values()]);
  }

  /**
   * To be executed when a chip filter has been enabled/disabled
   * @param setting The value of the filter
   */
  stateChanged(setting: SCSetting) {
    if (this.filtersMap.get(setting.name as NewsFilterSettingsNames) === undefined) {
      this.filtersMap.set(
        setting.name as NewsFilterSettingsNames,
        DataProvider.createValueFilter(
          newsFilterSettingsFieldsMapping[setting.name as NewsFilterSettingsNames],
          setting.value as string,
        ),
      );
    } else {
      this.filtersMap.delete(setting.name as NewsFilterSettingsNames);
    }

    this.filtersChanged.emit([...this.filtersMap.values()]);
  }
}
