import { Injectable } from '@nestjs/common';
import { WidgetInterface } from './widget-interface';
import { ListIssuesByFieldsWidgetDataLoaderService } from './widget-data-loader/list-issues-by-fields.widget-data-loader.service';
import { ListIssuesByUsersLikeJiraWidgetDataLoaderService } from './widget-data-loader/list-issues-by-users-like-jira.widget-data-loader.service';
import { RootIssueSubTreesWidgetDataLoaderService } from './widget-data-loader/root-issue-subtrees.widget-data-loader.service';
import { createInteractiveWidget } from './interactive-widget-factory';
import { Result, success } from '@app/event-emitter/utils/result';
import { CalendarWidgetDataLoaderService } from './widget-data-loader/calendar.widget-data-loader.service';

@Injectable()
export class WidgetsCollectionService {
  collection: WidgetInterface<any, any, any, any, any>[] = [];

  constructor(
    private listIssuesByFieldsWidgetDataLoaderService: ListIssuesByFieldsWidgetDataLoaderService,
    private listIssuesByUsersLikeJiraWidgetDataLoaderService: ListIssuesByUsersLikeJiraWidgetDataLoaderService,
    private rootIssueSubTreesWidgetDataLoaderService: RootIssueSubTreesWidgetDataLoaderService,
    private calendarWidgetDataLoaderService: CalendarWidgetDataLoaderService,
  ) {
    const collection = [
      createInteractiveWidget(
        this.listIssuesByFieldsWidgetDataLoaderService,
        'kanban_by_fields',
      ),
      createInteractiveWidget(
        this.listIssuesByUsersLikeJiraWidgetDataLoaderService,
        'kanban_by_users',
      ),
      createInteractiveWidget(
        this.rootIssueSubTreesWidgetDataLoaderService,
        'kanban_by_tree',
      ),
      createInteractiveWidget(
        this.listIssuesByFieldsWidgetDataLoaderService,
        'issues_list_by_fields',
      ),
      createInteractiveWidget(
        this.listIssuesByUsersLikeJiraWidgetDataLoaderService,
        'issues_list_by_users',
      ),
      createInteractiveWidget(
        this.rootIssueSubTreesWidgetDataLoaderService,
        'issues_list_by_tree',
      ),
      createInteractiveWidget(
        this.calendarWidgetDataLoaderService,
        'calendar_next_events',
      ),
    ];

    collection.forEach((w) => this.appendWidget(w));
  }

  appendWidget(
    widget: WidgetInterface<any, any, any, any, any>,
  ): Result<true, string> {
    const type = widget.type;
    const isExists = this.collection.find((w) => w.type === type);
    if (isExists) return fail('WIDGET_WITH_SAME_TYPE_ALREADY_EXISTS');
    this.collection.push(widget);
    return success(true);
  }

  getWidgetTypes(): string[] {
    return this.collection.map((w) => w.type);
  }

  getWidgetByType(
    type: string,
  ): Result<WidgetInterface<any, any, any, any, any>, string> {
    const widget = this.collection.find((w) => w.type === type);
    return widget ? success(widget) : fail('WIDGET_WITH_SAME_TYPE_NOT_FOUND');
  }
}
