import { Component, h, Host, Prop, State, Watch } from '@stencil/core';
import ApolloClient from 'apollo-boost';
import { GET_DATASET } from './queries';
import { getEstimatedResultSizes } from './utilities';
import { byteFormat } from '../../shared/utils';
import get from 'lodash.get';
export class GdSubsetData {
  constructor() {
    /**
     * an array of the fetched datset's services
     */
    this.datasetServices = [];
    /**
     * used to notify user when a dataset is being fetched
     */
    this.loadingDataset = false;
    /**
     * any errors encountered while loading the dataset
     */
    this.errorLoadingDataset = false;
    /**
     * flags to determine when to show reset buttons on the accordion headers
     */
    this.showDownloadMethodResetButton = false;
    this.client = new ApolloClient({
      uri: 'http://localhost:4000/graphql',
    });
  }
  componentDidLoad() {
    this.fetchDataset();
  }
  async fetchDataset() {
    var _a;
    if (!this.datasetIdentifier)
      return;
    // reset all selections as we're changing the dataset
    this.reset();
    // notify user that we're loading the dataset
    this.loadingDataset = true;
    try {
      // query GraphQL for the dataset with services
      const result = await this.client.query({
        query: GET_DATASET,
        variables: {
          identifier: this.datasetIdentifier,
        },
      });
      // set the fetched dataset on state
      this.dataset = (_a = result === null || result === void 0 ? void 0 : result.data) === null || _a === void 0 ? void 0 : _a.dataset;
    }
    catch (err) {
      console.error('failed to load ', err);
      this.dataset = null;
      this.errorLoadingDataset = true;
    }
    finally {
      // stop loading
      this.loadingDataset = false;
    }
  }
  /**
   * actions to take whenever a new dataset is loaded
   */
  datasetLoaded() {
    // retrieve subset services and convert to an array
    this.datasetServices = get(this.dataset, 'services.subset');
    // set the selected service back to the default
    this.setSelectedService();
  }
  /**
   * resets the state to the default, removing any user selections
   */
  reset() {
    this.errorLoadingDataset = false; // remove any visible errors
    this.dataset = null; // delete the dataset response
  }
  /**
   * default service will either be the OpenSearch service OR if only one service is passed in, we'll use that one
   *
   * @param service
   * @returns
   */
  isDefaultService(service) {
    var _a;
    return service.serviceAgent == 'OpenSearch' || ((_a = this.datasetServices) === null || _a === void 0 ? void 0 : _a.length) == 1;
  }
  /**
   * sets the selected service or sets it to the default service
   * @param service
   */
  setSelectedService(service) {
    var _a;
    // enable the reset button if a service is selected by the user
    this.showDownloadMethodResetButton = service ? true : false;
    // set the selected service
    this.selectedService = service || ((_a = this.datasetServices) === null || _a === void 0 ? void 0 : _a.find(service => this.isDefaultService(service)));
  }
  render() {
    var _a, _b, _c;
    let estimatedResultSizes;
    if (this.dataset) {
      estimatedResultSizes = getEstimatedResultSizes(
      // TODO: CHANGE THESE BEFORE COMMIT*******************************************
      '2020-01-01', '2021-03-01', (_a = this.dataset) === null || _a === void 0 ? void 0 : _a.granulesPerDayPredicted, (_b = this.dataset) === null || _b === void 0 ? void 0 : _b.fileSizePredicted, (_c = this.dataset) === null || _c === void 0 ? void 0 : _c.fileSizeComputed);
    }
    return (h(Host, null,
      this.loadingDataset && h("div", null, "Retrieving dataset..."),
      this.dataset && (h("form", null,
        h("div", null,
          estimatedResultSizes && (h("div", { class: "my-3" },
            h("h5", null, "Estimated size of results"),
            h("small", null,
              h("strong", null, estimatedResultSizes.days),
              " days, ",
              h("strong", null, estimatedResultSizes.links),
              " links,",
              ' ',
              h("strong", null, byteFormat(estimatedResultSizes.fileSize))))),
          h("h5", null,
            "Download Method",
            h("gd-help", null)),
          h("bs-collapse", { name: "Download Method: ", "collapse-id": "download-method" },
            h("span", { slot: "header-left" }, "test"),
            h("div", { slot: "header-right" },
              h("bs-button", { disabled: !this.showDownloadMethodResetButton, size: "sm", variant: "secondary", onClick: e => {
                  e.stopPropagation(); // stops button click from activating accordion
                  if (this.showDownloadMethodResetButton) {
                    this.setSelectedService(); // reset back to default
                  }
                } }, "Reset")),
            h("download-method", { services: this.datasetServices, selectedService: this.selectedService, onServiceChange: ({ detail: service }) => this.setSelectedService(service) })),
          h("h5", null, "Method Options"),
          h("bs-collapse", { name: "Refine Date Range", "collapse-id": "refine-date-range" },
            h("p", null, "Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.")),
          h("h5", null, "Output Format"),
          h("bs-collapse", { name: "File Format", "collapse-id": "refine-date-range" },
            h("p", null, "Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS."))))),
      this.errorLoadingDataset && h("div", { class: "alert alert-danger" }, "Failed to retrieve dataset")));
  }
  static get is() { return "gd-subset-data"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() { return {
    "$": ["gd-subset-data.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["gd-subset-data.css"]
  }; }
  static get properties() { return {
    "datasetIdentifier": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "short name + version of a dataset (ex. GLDAS_NOAH025_3H_2.1)"
      },
      "attribute": "dataset-identifier",
      "reflect": false
    }
  }; }
  static get states() { return {
    "dataset": {},
    "datasetServices": {},
    "loadingDataset": {},
    "errorLoadingDataset": {},
    "selectedService": {},
    "showDownloadMethodResetButton": {}
  }; }
  static get watchers() { return [{
      "propName": "datasetIdentifier",
      "methodName": "fetchDataset"
    }, {
      "propName": "dataset",
      "methodName": "datasetLoaded"
    }]; }
}
