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 {
  Domain,
  DomainCreateInput,
  DomainUpdateInput,
} from 'src/app/model/entities/domain';
import { PageWithHistoryDataService } from 'src/app/core/base/page-with-history.data.service';

@Injectable()
export class DomainsDataService
  extends PageWithHistoryDataService<Domain>
  implements
    Create<Domain, DomainCreateInput>,
    Update<Domain, DomainUpdateInput>,
    Delete<Domain>,
    Restore<Domain>
{
  constructor(
    private spinner: SpinnerService,
    private apollo: Apollo
  ) {
    super();
  }

  load(
    filter?: Filter[] | undefined,
    sort?: Sort[] | undefined,
    skip?: number | undefined,
    take?: number | undefined
  ): Observable<QueryResult<Domain>> {
    return this.apollo
      .query<{ domains: QueryResult<Domain> }>({
        query: gql`
          query getDomains(
            $filter: [DomainFilter]
            $sort: [DomainSort]
            $skip: Int
            $take: Int
          ) {
            domains(filter: $filter, sort: $sort, skip: $skip, take: $take) {
              count
              totalCount
              nodes {
                id
                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.domains));
  }

  loadById(id: number): Observable<Domain> {
    return this.apollo
      .query<{ domains: QueryResult<Domain> }>({
        query: gql`
          query getDomain($id: Int) {
            domain(filter: { id: { equal: $id } }) {
              id
              name

              ...DB_MODEL
            }
          }

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

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

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

  create(object: DomainCreateInput): Observable<Domain | undefined> {
    return this.apollo
      .mutate<{ domain: { create: Domain } }>({
        mutation: gql`
          mutation createDomain($input: DomainCreateInput!) {
            domain {
              create(input: $input) {
                id
                name

                ...DB_MODEL
              }
            }
          }

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

  update(object: DomainUpdateInput): Observable<Domain | undefined> {
    return this.apollo
      .mutate<{ domain: { update: Domain } }>({
        mutation: gql`
          mutation updateDomain($input: DomainUpdateInput!) {
            domain {
              update(input: $input) {
                id
                name

                ...DB_MODEL
              }
            }
          }

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

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

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

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