<b-row>
  <b-col cols="12" class="mb-3">
    <h2>Wellness: {{ stats.percent.toFixed(1) }}%</h2>
    <b-progress v-bind:value="stats.percent" v-bind:variant="stats.color" height="30px"></b-progress>
  </b-col>
  <b-col cols="12" class="h5 mb-3">
    Showing <b-badge pill variant="dark">{{ wellness.length }}</b-badge> wellness events.
  </b-col>
  <b-col v-for="event in wellness" cols="12" sm="6" lg="4" class="mb-3">
    <b-card no-body class="h-100">
      <b-card-body class="pb-0">
        <b-card-title>{{ event.title }}</b-card-title>
        <b-card-sub-title class="mb-2">Wellness Event</b-card-sub-title>
      </b-card-body>
      <b-list-group flush>
        <b-list-group-item>
          <b class="w-25 d-inline-block">Between:</b>
          {{ event.startTime }}<br />
          <div class="w-25 d-inline-block">&nbsp;</div>
          {{ event.endTime }}
        </b-list-group-item>
        <b-list-group-item><b class="w-25 d-inline-block">Value:</b> {{ event.displayTotal }}</b-list-group-item>
      </b-list-group>
      <b-card-footer class="text-truncate" v-bind:title="event.source">{{ event.source }}</b-card-footer>
    </b-card>
  </b-col>
</b-row>

<%- contentFor("ContentScripts") %>

<script type="text/javascript">
  (function () {
    'use strict';

    var data = {},
      computed = {};

    data.wellness = [];

    function transform(data) {
      // ignore merge data
      data = _.filter(data, function (obj) {
        return !_.includes(obj.originDataSourceId, ':merge_') && !_.includes(obj.dataTypeName, 'speed.summary');
      });
      // ignore duplicate data
      data = _.uniqBy(data, JSON.stringify);
      // transform the data for usage
      return _.reduce(
        data,
        function (memo, record) {
          var event = {},
            nanoPerMilli = 1000000;

          // transform the start and end time into a locale string
          event.startTime = moment(record.startTimeNanos / nanoPerMilli).format('MMM DD, YYYY HH:mm A');
          event.endTime = moment(record.endTimeNanos / nanoPerMilli).format('MMM DD, YYYY HH:mm A');
          // transform the data type name into an event title
          var title = record.dataTypeName || '';
          title = title.replace('com.google.', '').replace(/\./g, '_').replace('_delta', '');
          event.title = _.startCase(title);
          // clean and delimit the data source
          var source = (record.originDataSourceId || '').split(':');
          source.shift(); // ignore type
          event.source = source.join(' | ').replace(/com\..*?\./g, '');

          var total = 0;
          _.forEach(record.value, function (value) {
            _.forOwn(value, function (obj) {
              if (typeof obj === 'number') total += obj;
            });
          });
          event.total = total;

          // generate a display total
          if (total >= 3600000) total = moment.duration(total).humanize(); // 1 hour
          if (total >= 60000) total = moment.duration(total).humanize(); // 1 minute
          if (typeof total === 'number' && _.includes(event.title, 'Minutes')) total = `${total} minutes`;
          event.displayTotal = total;

          memo.push(event);
          return memo;
        },
        []
      );
    }

    computed.stats = function () {
      var rawData = _.cloneDeep(this.wellness);

      var filterData = _.filter(rawData, function (event) {
        return _.includes(event.source, 'my.wellness.complete') || _.includes(event.source, 'sleep');
      });

      var mental = 0;
      _.forEach(filterData, function (obj) {
        console.log(obj);
        mental += obj.total;
      });

      var mentalTotal = 57600000; // 16 hours over the 48 hour period
      var result = (mental / mentalTotal) * 100;
      var color = 'success';
      if (result < 50) color = 'warning';
      if (result < 15) color = 'danger';

      return {
        percent: result,
        color: color,
      };
    };

    function mounted() {
      axios
        .get('/api/wellness')
        .then((response) => {
          var data = transform(response.data.wellness);

          _.forEach(loadFromLocalStorage().wellness, function (event) {
            data.push(event);
          });

          if (response.data) this.wellness = data;
        })
        .catch((error) => {
          this.alert = error.response.data;
        });
    }

    window.Bundle = {
      data: data,
      computed: computed,
      mounted: mounted,
    };
  })();
</script>
