import { Injectable, Provider } from '@angular/core';
import { merge, 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, SortOrder } 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 {
  UserSpace,
  UserSpaceCreateInput,
  UserSpaceUpdateInput,
} from 'src/app/model/entities/user-space';
import { PageWithHistoryDataService } from 'src/app/core/base/page-with-history.data.service';

@Injectable()
export class UserSpacesDataService
  extends PageDataService<UserSpace>
  implements
    Create<UserSpace, UserSpaceCreateInput>,
    Update<UserSpace, UserSpaceUpdateInput>,
    Delete<UserSpace>,
    Restore<UserSpace>
{
  constructor(
    private spinner: SpinnerService,
    private apollo: Apollo
  ) {
    super();
  }

  load(
    filter?: Filter[] | undefined,
    sort?: Sort[] | undefined,
    skip?: number | undefined,
    take?: number | undefined
  ): Observable<QueryResult<UserSpace>> {
    return this.apollo
      .query<{ userSpaces: QueryResult<UserSpace> }>({
        query: gql`
          query getUserSpaces(
            $filter: [UserSpaceFilter]
            $sort: [UserSpaceSort]
          ) {
            userSpaces(filter: $filter, sort: $sort) {
              nodes {
                id
                name
                owner {
                  id
                  username
                }

                ...DB_MODEL
              }
            }
          }

          ${DB_MODEL_FRAGMENT}
        `,
        variables: {
          filter: [filter],
          sort: [{ id: SortOrder.DESC }, ...(sort ?? [])],
          skip,
          take,
        },
      })
      .pipe(map(result => result.data.userSpaces));
  }

  loadById(id: number): Observable<UserSpace> {
    return this.apollo
      .query<{ userSpaces: QueryResult<UserSpace> }>({
        query: gql`
          query getUserSpace($id: Int) {
            userSpaces(filter: { id: { equal: $id } }) {
              nodes {
                id
                name

                owner {
                  id
                  username
                }

                users {
                  id
                  username
                }

                ...DB_MODEL
              }
            }
          }

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

  loadHistory(id: number) {
    return this.apollo
      .query<{ userSpaces: QueryResult<UserSpace> }>({
        query: gql`
          query getUserSpaceHistory($id: Int) {
            userSpaces(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?.userSpaces?.nodes?.[0]?.history ?? []));
  }

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

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

  create(object: UserSpaceCreateInput): Observable<UserSpace | undefined> {
    return this.apollo
      .mutate<{ userSpace: { create: UserSpace } }>({
        mutation: gql`
          mutation createUserSpace($input: UserSpaceCreateInput!) {
            userSpace {
              create(input: $input) {
                id
                name

                ...DB_MODEL
              }
            }
          }

          ${DB_MODEL_FRAGMENT}
        `,
        variables: {
          input: {
            name: object.name,
            users: object.users,
          },
        },
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data?.userSpace.create));
  }

  update(object: UserSpaceUpdateInput): Observable<UserSpace | undefined> {
    return this.apollo
      .mutate<{ userSpace: { update: UserSpace } }>({
        mutation: gql`
          mutation updateUserSpace($input: UserSpaceUpdateInput!) {
            userSpace {
              update(input: $input) {
                id
                name

                ...DB_MODEL
              }
            }
          }

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

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

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

  inviteUsers(id: number, emails: string[]): Observable<boolean> {
    return this.apollo
      .mutate<{ userSpace: { inviteUsers: boolean } }>({
        mutation: gql`
          mutation inviteUsers($id: Int!, $emails: [String!]!) {
            userSpace {
              inviteUsers(id: $id, emails: $emails)
            }
          }
        `,
        variables: {
          id,
          emails,
        },
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data?.userSpace.inviteUsers ?? false));
  }

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