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 } 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 {
  ApiKey,
  ApiKeyCreateInput,
  ApiKeyUpdateInput,
} from 'src/app/model/entities/api-key';
import { PageWithHistoryDataService } from 'src/app/core/base/page-with-history.data.service';
import { DbModel } from 'src/app/model/entities/db-model';

@Injectable()
export class ApiKeysDataService
  extends PageWithHistoryDataService<ApiKey>
  implements
    Create<ApiKey, ApiKeyCreateInput>,
    Update<ApiKey, ApiKeyUpdateInput>,
    Delete<ApiKey>,
    Restore<ApiKey>
{
  constructor(
    private spinner: SpinnerService,
    private apollo: Apollo
  ) {
    super();
  }

  load(
    filter?: Filter[] | undefined,
    sort?: Sort[] | undefined,
    skip?: number | undefined,
    take?: number | undefined
  ): Observable<QueryResult<ApiKey>> {
    return this.apollo
      .query<{ apiKeys: QueryResult<ApiKey> }>({
        query: gql`
          query getApiKeys(
            $filter: [ApiKeyFilter]
            $sort: [ApiKeySort]
            $skip: Int
            $take: Int
          ) {
            apiKeys(filter: $filter, sort: $sort, skip: $skip, take: $take) {
              count
              totalCount
              nodes {
                id
                identifier
                key
                permissions {
                  name
                }

                ...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.apiKeys));
  }

  loadById(id: number): Observable<ApiKey> {
    return this.apollo
      .query<{ apiKeys: QueryResult<ApiKey> }>({
        query: gql`
          query getApiKey($id: Int) {
            apiKey(filter: { id: { equal: $id } }) {
              id
              identifier
              permissions {
                name
              }

              ...DB_MODEL
            }
          }

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

  loadHistory(id: number): Observable<DbModel[]> {
    return this.apollo
      .query<{ apiKeys: QueryResult<ApiKey> }>({
        query: gql`
          query getApiKeyHistory($id: Int) {
            apiKeys(filter: { id: { equal: $id } }) {
              count
              totalCount
              nodes {
                history {
                  id
                  identifier
                  permissions {
                    name
                  }

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

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

  create(object: ApiKeyCreateInput): Observable<ApiKey | undefined> {
    return this.apollo
      .mutate<{ apiKey: { create: ApiKey } }>({
        mutation: gql`
          mutation createApiKey($input: ApiKeyCreateInput!) {
            apiKey {
              create(input: $input) {
                id
                identifier
                permissions {
                  name
                }

                ...DB_MODEL
              }
            }
          }

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

  update(object: ApiKeyUpdateInput): Observable<ApiKey | undefined> {
    return this.apollo
      .mutate<{ apiKey: { update: ApiKey } }>({
        mutation: gql`
          mutation updateApiKey($input: ApiKeyUpdateInput!) {
            apiKey {
              update(input: $input) {
                id
                identifier
                permissions {
                  name
                }

                ...DB_MODEL
              }
            }
          }

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

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

  restore(object: ApiKey): Observable<boolean> {
    return this.apollo
      .mutate<{ apiKey: { restore: boolean } }>({
        mutation: gql`
          mutation restoreApiKey($id: Int!) {
            apiKey {
              restore(id: $id)
            }
          }
        `,
        variables: {
          id: object.id,
        },
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data?.apiKey.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: ApiKeysDataService,
      },
      {
        provide: PageWithHistoryDataService,
        useClass: ApiKeysDataService,
      },
      ApiKeysDataService,
    ];
  }
}
