/*
 * Copyright (C) 2018-2021 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {Injectable} from '@angular/core';
import {Client} from '@openstapps/api/lib/client';
import {SCDaiaAvailabilityResponse, SCDaiaHoldings} from './protocol/response';
import {StorageProvider} from '../storage/storage.provider';
import {StAppsWebHttpClient} from '../data/stapps-web-http-client.provider';
import {HttpClient} from '@angular/common/http';
import {DataProvider} from '../data/data.provider';
import {environment} from '../../../environments/environment';

/**
 *  Generated class for the DataProvider provider.
 *
 * See https://angular.io/guide/dependency-injection for more info on providers
 * and Angular DI.
 */
@Injectable({
  providedIn: 'root',
})
export class DaiaDataProvider extends DataProvider {
  /**
   * TODO
   */
  storageProvider: StorageProvider;

  httpClient: HttpClient;

  backendUrl = environment.daia_url;

  /**
   * TODO
   *
   * @param stAppsWebHttpClient TODO
   * @param storageProvider TODO
   * @param httpClient TODO
   */
  constructor(
    stAppsWebHttpClient: StAppsWebHttpClient,
    storageProvider: StorageProvider,
    httpClient: HttpClient,
  ) {
    super(stAppsWebHttpClient, storageProvider);
    this.storageProvider = storageProvider;
    this.httpClient = httpClient;
    this.client = new Client(
      stAppsWebHttpClient,
      this.backendUrl,
      this.appVersion,
    );
  }

  async getAvailability(id: string): Promise<SCDaiaHoldings[]> {
    return new Promise(resolve =>
      this.httpClient
        .get<SCDaiaAvailabilityResponse>(this.backendUrl, {params: {id}})
        .subscribe((response: SCDaiaAvailabilityResponse) => {
          console.error(response);
          const holdings: SCDaiaHoldings[] = [];
          if (response && Array.isArray(response.document)) {
            response.document.map(document => {
              Array.isArray(document.item) &&
                document.item.map(element => {
                  try {
                    const {
                      department: {
                        id: departmentId,
                        content: departmentLabel,
                        href: departmentLink,
                      } = {id: 'noDep', content: '', href: ''},
                      label,
                      about,
                      available,
                      storage,
                    } = element;
                    const holdingIndex = holdings.findIndex(
                      holding => holding.id === departmentId,
                    );

                    if (holdingIndex === -1) {
                      holdings.push({
                        id: departmentId,
                        label: departmentLabel,
                        href: departmentLink,
                        signature: label,
                        available:
                          (Array.isArray(available) &&
                            (available.find(
                              item => item.service === 'openaccess',
                            ) ||
                              available.find(
                                item => item.service === 'loan',
                              ))) ||
                          undefined,
                        storage,
                        about,
                      });
                    }
                  } catch {
                    // No element available
                  }
                });
            });
          }
          resolve(holdings);
        }),
    );
  }
}
