import { ApolloQuery, html } from '@apollo-elements/lit-apollo';

/* Utils */
import { apollo } from '@ppci/utils';
import gql from 'graphql-tag';

/* Styles */
import style from './style';

/* Components */
import '@ppci/pie-chart';

const query = gql`
  query {
    readings @rest(type: "ReadingsPayload", path: "Readings/total/usage", endpoint: "allocation") {
      total
      data @type(name: "Readings") {
        category
        energyType
        usageE
      }
    }
  }
`;

export class UsageOrigin extends ApolloQuery {
  constructor() {
    super();
    this.client = apollo;
    this.query = query;
    this.loading = true;
  }

  static get styles() {
    return style;
  }

  get renderLoader() {
    return html`
      loading...
    `;
  }

  get renderUsage() {
    const { data = { readings: { data: [] } } } = this;
    const { readings } = data;
    const { total } = readings;
    const readingData = readings.data;
    const colors = [
      '#845EC2',
      '#D65DB1',
      'FF6F91',
    ];
    const names = [
      'Backup',
      'Social',
      'Local',
    ];

    if (readingData.length === 0) return 'no data';

    const graphData = readingData.map((reading) => {
      const categoryId = reading.category || 0;
      const color = colors[categoryId];
      const name = names[categoryId] || 'unknown';

      return {
        color,
        value: reading.usageE,
        name,
      };
    });
    return html`
      <pie-chart .data=${graphData}></pie-chart>
    `;
  }

  render() {
    const { loading, error } = this;
    const fetchError = error
      ? {
        title: 'Something went wrong.',
        message: error,
        retryTitle: 'Try again',
        retryAction: () => { this.refetch(); },
      }
      : null;

    return html`
      <widget-wrapper .error=${fetchError}>
        ${loading ? this.renderLoader : this.renderUsage}
      </widget-wrapper>
    `;
  }
}

customElements.define('usage-origin', UsageOrigin);
