/*
 * 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 {Injectable} from '@angular/core';
import {
  SCBooleanFilterArguments,
  SCMessage,
  SCSearchBooleanFilter,
  SCSearchFilter,
  SCSearchQuery,
} from '@openstapps/core';
import {DataProvider} from '../data/data.provider';
/**
 * Service for providing catalog and semester data
 */
@Injectable({
  providedIn: 'root',
})
export class DashboardProvider {
  constructor(private readonly dataProvider: DataProvider) {}

  /**
   * Get news messages
   * @param size How many messages/news to fetch
   * @param from From which (results) page to start
   * @param filters Additional filters to apply
   */
  async getNews(size: number, from: number, filters?: SCSearchFilter[]): Promise<SCMessage[]> {
    const query: SCSearchQuery = {
      filter: {
        type: 'boolean',
        arguments: {
          filters: [
            {
              type: 'value',
              arguments: {
                field: 'type',
                value: 'message',
              },
            },
          ],
          operation: 'and',
        },
      },
      sort: [
        {
          type: 'generic',
          arguments: {
            field: 'datePublished',
          },
          order: 'desc',
        },
      ],
      size: size,
      from: from,
    };

    if (filters !== undefined) {
      for (const filter of filters) {
        ((query.filter as SCSearchBooleanFilter).arguments as SCBooleanFilterArguments).filters.push(filter);
      }
    }

    const result = await this.dataProvider.search(query);

    return result.data as SCMessage[];
  }
}
