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_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 {
  ShortUrl,
  ShortUrlCreateInput,
  ShortUrlUpdateInput,
} from 'src/app/model/entities/short-url';
import { Group } from 'src/app/model/entities/group';
import { Domain } from 'src/app/model/entities/domain';

@Injectable()
export class ShortUrlsDataService
  extends PageDataService<ShortUrl>
  implements
    Create<ShortUrl, ShortUrlCreateInput>,
    Update<ShortUrl, ShortUrlUpdateInput>,
    Delete<ShortUrl>,
    Restore<ShortUrl>
{
  constructor(
    private spinner: SpinnerService,
    private apollo: Apollo
  ) {
    super();
  }

  load(
    filter?: Filter[] | undefined,
    sort?: Sort[] | undefined,
    skip?: number | undefined,
    take?: number | undefined
  ): Observable<QueryResult<ShortUrl>> {
    return this.apollo
      .query<{ shortUrls: QueryResult<ShortUrl> }>({
        query: gql`
          query getShortUrls(
            $filter: [ShortUrlFilter]
            $sort: [ShortUrlSort]
            $skip: Int
            $take: Int
          ) {
            shortUrls(filter: $filter, sort: $sort, skip: $skip, take: $take) {
              count
              totalCount
              nodes {
                id
                shortUrl
                targetUrl
                description
                loadingScreen
                visits
                group {
                  id
                  name
                }
                domain {
                  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.shortUrls));
  }

  loadById(id: number): Observable<ShortUrl> {
    return this.apollo
      .query<{ shortUrls: QueryResult<ShortUrl> }>({
        query: gql`
          query getShortUrl($id: Int) {
            shortUrl(filter: { id: { equal: $id } }) {
              id
              shortUrl
              targetUrl
              description
              loadingScreen
              visits
              group {
                id
                name
              }
              domain {
                id
                name
              }

              ...DB_MODEL
            }
          }

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

  create(object: ShortUrlCreateInput): Observable<ShortUrl | undefined> {
    return this.apollo
      .mutate<{ shortUrl: { create: ShortUrl } }>({
        mutation: gql`
          mutation createShortUrl($input: ShortUrlCreateInput!) {
            shortUrl {
              create(input: $input) {
                id
                description

                ...DB_MODEL
              }
            }
          }

          ${DB_MODEL_FRAGMENT}
        `,
        variables: {
          input: {
            shortUrl: object.shortUrl,
            targetUrl: object.targetUrl,
            description: object.description,
            loadingScreen: object.loadingScreen,
            groupId: object.groupId,
            domainId: object.domainId,
          },
        },
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data?.shortUrl.create));
  }

  update(object: ShortUrlUpdateInput): Observable<ShortUrl | undefined> {
    return this.apollo
      .mutate<{ shortUrl: { update: ShortUrl } }>({
        mutation: gql`
          mutation updateShortUrl($input: ShortUrlUpdateInput!) {
            shortUrl {
              update(input: $input) {
                id
                description

                ...DB_MODEL
              }
            }
          }

          ${DB_MODEL_FRAGMENT}
        `,
        variables: {
          input: {
            id: object.id,
            shortUrl: object.shortUrl,
            targetUrl: object.targetUrl,
            description: object.description,
            loadingScreen: object.loadingScreen,
            groupId: object.groupId,
            domainId: object.domainId,
          },
        },
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data?.shortUrl.update));
  }

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

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

  getAllGroups() {
    return this.apollo
      .query<{ groups: QueryResult<Group> }>({
        query: gql`
          query getGroups {
            groups {
              nodes {
                id
                name
              }
            }
          }
        `,
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data.groups.nodes));
  }

  getAllDomains() {
    return this.apollo
      .query<{ domains: QueryResult<Domain> }>({
        query: gql`
          query getGroups {
            domains {
              nodes {
                id
                name
              }
            }
          }
        `,
      })
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .pipe(map(result => result.data.domains.nodes));
  }

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