import { Injectable, Provider } from '@angular/core';
import { Observable } from 'rxjs';
import {
  Create,
  Delete,
  PageDataService,
  Restore,
  Update,
} from 'src/app/core/base/page.data.service';
import { Filter } from 'src/app/model/graphql/filter/filter.model';
import { Sort } from 'src/app/model/graphql/filter/sort.model';
import { Apollo, gql } from 'apollo-angular';
import { QueryResult } from 'src/app/model/entities/query-result';
import {
  DB_HISTORY_MODEL_FRAGMENT,
  DB_MODEL_FRAGMENT,
} from 'src/app/model/graphql/db-model.query';
import { catchError, map } from 'rxjs/operators';
import { SpinnerService } from 'src/app/service/spinner.service';
import {
  Group,
  GroupCreateInput,
  GroupUpdateInput,
} from 'src/app/model/entities/group';
import { PageWithHistoryDataService } from 'src/app/core/base/page-with-history.data.service';
import { SidebarService } from 'src/app/service/sidebar.service';

@Injectable()
export class GroupsDataService
  extends PageWithHistoryDataService<Group>
  implements
    Create<Group, GroupCreateInput>,
    Update<Group, GroupUpdateInput>,
    Delete<Group>,
    Restore<Group>
{
  constructor(
    private spinner: SpinnerService,
    private apollo: Apollo,
    private sidebarService: SidebarService
  ) {
    super();
  }

  load(
    filter?: Filter[] | undefined,
    sort?: Sort[] | undefined,
    skip?: number | undefined,
    take?: number | undefined
  ): Observable<QueryResult<Group>> {
    return this.apollo
      .query<{ groups: QueryResult<Group> }>({
        query: gql`
          query getGroups(
            $filter: [GroupFilter]
            $sort: [GroupSort]
            $skip: Int
            $take: Int
          ) {
            groups(filter: $filter, sort: $sort, skip: $skip, take: $take) {
              count
              totalCount
              nodes {
                id
                name
                roles {
                  id
                  name
                }

                ...DB_MODEL
              }
            }
          }

          ${DB_MODEL_FRAGMENT}
        `,
        variables: {
          filter: [
            {
              userSpace: {
                id: { equal: this.sidebarService.selectedUserSpace$.value?.id },
              },
            },
            ...(filter ?? []),
          ],
          sort: sort,
          skip: skip,
          take: take,
        },
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data.groups));
  }

  loadById(id: number): Observable<Group> {
    return this.apollo
      .query<{ groups: QueryResult<Group> }>({
        query: gql`
          query getGroup($id: Int) {
            group(filter: { id: { equal: $id } }) {
              id
              name
              roles {
                id
                name
              }

              ...DB_MODEL
            }
          }

          ${DB_MODEL_FRAGMENT}
        `,
        variables: {
          id: id,
        },
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data.groups.nodes[0]));
  }

  loadHistory(id: number) {
    return this.apollo
      .query<{ groups: QueryResult<Group> }>({
        query: gql`
          query getGroupHistory($id: Int) {
            groups(filter: { id: { equal: $id } }) {
              count
              totalCount
              nodes {
                history {
                  id
                  name

                  ...DB_HISTORY_MODEL
                }
              }
            }
          }

          ${DB_HISTORY_MODEL_FRAGMENT}
        `,
        variables: {
          id,
        },
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data?.groups?.nodes?.[0]?.history ?? []));
  }

  onChange(): Observable<void> {
    return this.apollo
      .subscribe<{ groupChange: void }>({
        query: gql`
          subscription onGroupChange {
            groupChange
          }
        `,
      })
      .pipe(map(result => result.data?.groupChange));
  }

  create(object: GroupCreateInput): Observable<Group | undefined> {
    return this.apollo
      .mutate<{ group: { create: Group } }>({
        mutation: gql`
          mutation createGroup($input: GroupCreateInput!) {
            group {
              create(input: $input) {
                id
                name

                ...DB_MODEL
              }
            }
          }

          ${DB_MODEL_FRAGMENT}
        `,
        variables: {
          input: {
            userSpaceId: this.sidebarService.selectedUserSpace$.value?.id,
            name: object.name,
            roles: object.roles?.map(x => x.id),
          },
        },
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data?.group.create));
  }

  update(object: GroupUpdateInput): Observable<Group | undefined> {
    return this.apollo
      .mutate<{ group: { update: Group } }>({
        mutation: gql`
          mutation updateGroup($input: GroupUpdateInput!) {
            group {
              update(input: $input) {
                id
                name

                ...DB_MODEL
              }
            }
          }

          ${DB_MODEL_FRAGMENT}
        `,
        variables: {
          input: {
            id: object.id,
            name: object.name,
            roles: object.roles?.map(x => x.id),
          },
        },
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data?.group.update));
  }

  delete(object: Group): Observable<boolean> {
    return this.apollo
      .mutate<{ group: { delete: boolean } }>({
        mutation: gql`
          mutation deleteGroup($id: Int!) {
            group {
              delete(id: $id)
            }
          }
        `,
        variables: {
          id: object.id,
        },
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data?.group.delete ?? false));
  }

  restore(object: Group): Observable<boolean> {
    return this.apollo
      .mutate<{ group: { restore: boolean } }>({
        mutation: gql`
          mutation restoreGroup($id: Int!) {
            group {
              restore(id: $id)
            }
          }
        `,
        variables: {
          id: object.id,
        },
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data?.group.restore ?? false));
  }

  static provide(): Provider[] {
    return [
      {
        provide: PageDataService,
        useClass: GroupsDataService,
      },
      {
        provide: PageWithHistoryDataService,
        useClass: GroupsDataService,
      },
      GroupsDataService,
    ];
  }
}
