import { Inject, Injectable } from '@nestjs/common';
import { WidgetDataLoaderInterface } from '../widget-data-loader-interface';
import {
  Result,
  AppError,
  success,
  fail,
  createAppError,
} from '@app/event-emitter/utils/result';
import {
  CalendarService,
  IssueAndEvent,
} from '@app/event-emitter/calendar/calendar.service';
import nano from 'nano';

export type DataLoaderParams = {
  /** Период для выборки предстоящих событий в днях */
  period: number;
  /** Фильтр для выборки данных из couchdb */
  filter: nano.MangoQuery;
};

@Injectable()
export class CalendarWidgetDataLoaderService
  implements WidgetDataLoaderInterface<DataLoaderParams, any, IssueAndEvent[]>
{
  constructor(
    @Inject('CALENDAR_SERVICE') private calendarService: CalendarService,
  ) {}

  isMyConfig(): boolean {
    return true;
  }

  async load(
    dataLoaderParams: DataLoaderParams,
  ): Promise<Result<IssueAndEvent[], AppError>> {
    let data: IssueAndEvent[];
    try {
      data = await this.calendarService.getRawData(
        dataLoaderParams.filter,
        dataLoaderParams.period * 24 * 60 * 60 * 1000,
      );
      return success(data);
    } catch (ex) {
      return fail(createAppError(ex.message ? ex.message : 'UNKNOWN_ERROR'));
    }
  }
}
