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 {
  Permission,
  Role,
  RoleCreateInput,
  RoleUpdateInput,
} from 'src/app/model/entities/role';
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 { PageWithHistoryDataService } from 'src/app/core/base/page-with-history.data.service';
import { DbModel } from 'src/app/model/entities/db-model';

@Injectable()
export class RolesDataService
  extends PageWithHistoryDataService<Role>
  implements
    Create<Role, RoleCreateInput>,
    Update<Role, RoleUpdateInput>,
    Delete<Role>,
    Restore<Role>
{
  constructor(
    private spinner: SpinnerService,
    private apollo: Apollo
  ) {
    super();
  }

  load(
    filter?: Filter[] | undefined,
    sort?: Sort[] | undefined,
    skip?: number | undefined,
    take?: number | undefined
  ): Observable<QueryResult<Role>> {
    return this.apollo
      .query<{ roles: QueryResult<Role> }>({
        query: gql`
          query getRoles(
            $filter: [RoleFilter]
            $sort: [RoleSort]
            $skip: Int
            $take: Int
          ) {
            roles(filter: $filter, sort: $sort, skip: $skip, take: $take) {
              count
              totalCount
              nodes {
                id
                name
                description
                users {
                  id
                  username
                }

                ...DB_MODEL
              }
            }
          }

          ${DB_MODEL_FRAGMENT}
        `,
        variables: {
          filter: filter,
          sort: sort,
          skip: skip,
          take: take,
        },
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data.roles));
  }

  loadById(id: number): Observable<Role> {
    return this.apollo
      .query<{ roles: QueryResult<Role> }>({
        query: gql`
          query getRoles($id: Int) {
            roles(filter: { id: { equal: $id } }) {
              count
              totalCount
              nodes {
                id
                name
                description
                permissions {
                  id
                  name
                }
                users {
                  id
                  username
                }

                ...DB_MODEL
              }
            }
          }

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

  loadHistory(id: number): Observable<DbModel[]> {
    return this.apollo
      .query<{ roles: QueryResult<Role> }>({
        query: gql`
          query getRoleHistory($id: Int) {
            roles(filter: { id: { equal: $id } }) {
              count
              totalCount
              nodes {
                history {
                  id

                  name
                  description
                  permissions {
                    name
                  }

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

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

  create(object: RoleCreateInput): Observable<Role | undefined> {
    return this.apollo
      .mutate<{ role: { create: Role } }>({
        mutation: gql`
          mutation createRole($input: RoleCreateInput!) {
            role {
              create(input: $input) {
                id
                name
                description
                permissions {
                  name
                }

                ...DB_MODEL
              }
            }
          }

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

  update(object: RoleUpdateInput): Observable<Role | undefined> {
    return this.apollo
      .mutate<{ role: { update: Role } }>({
        mutation: gql`
          mutation updateRole($input: RoleUpdateInput!) {
            role {
              update(input: $input) {
                id
                name
                description
                permissions {
                  name
                }

                ...DB_MODEL
              }
            }
          }

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

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

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

  getAllPermissions(): Observable<Permission[]> {
    return this.apollo
      .query<{ permissions: QueryResult<Permission> }>({
        query: gql`
          query getPermissions {
            permissions(sort: [{ name: ASC }]) {
              nodes {
                id
                name
              }
            }
          }
        `,
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data.permissions.nodes));
  }

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