/** @jsx React.DOM */
/* 
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 * 
 * 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 License for more details.
 * 
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */
var _ = require('lodash');
var bows = require('bows');
var React = require('react');
var d3 = require('d3');

var Empty = require('./components/empty');
var Daily = require('./components/daily');
var Weekly = require('./components/weekly');
var Settings = require('./components/settings');
// tideline dependencies & plugins
var nurseshark = require('../plugins/nurseshark/');
var TidelineData = require('../js/tidelinedata');

var dt = require('../js/data/util/datetime');

require('../css/tideline.less');
require('./less/example.less');

var example = {
  log: bows('Example')
};

var dataUrl = process.env.DATA;
if (_.isEmpty(dataUrl)) {
  dataUrl = 'device-data.json';
}
dataUrl = 'data/' + dataUrl;

var Example = React.createClass({
  log: bows('Example'),
  componentDidMount: function() {
    this.fetchData();
  },
  getInitialState: function() {
    return {
      chartPrefs: {
        timePrefs: {
          timezoneAware: false,
          // timezoneAware: true,
          // timezoneName: 'Pacific/Auckland'
          // timezoneName: 'Europe/Paris'
          // timezoneName: 'US/Eastern'
          timezoneName: 'US/Pacific'
          // timezoneName: 'US/Hawaii'
        }
      },
      datetimeLocation: null,
      initialDatetimeLocation: null,
      chartType: 'empty'
    };
  },
  render: function() {
    var chart = this.renderChart();
    /* jshint ignore:start */
    return (
      <div>
        <div className="vSpace"></div>
          {chart}
        <div className="vSpace"></div>
      </div>
    );
    /* jshint ignore:end */
  },
  renderChart: function() {
    switch (this.state.chartType) {
      case 'empty':
        /* jshint ignore:start */
        return (
          <Empty />
          );
        /* jshint ignore:end */
      case 'daily':
        /* jshint ignore:start */
        return (
          <Daily
            bgPrefs={this.state.bgPrefs}
            chartPrefs={this.state.chartPrefs}
            initialDatetimeLocation={this.state.initialDatetimeLocation}
            patientData={this.state.chartData}
            onSwitchToDaily={this.handleSwitchToDaily}
            onSwitchToSettings={this.handleSwitchToSettings}
            onSwitchToWeekly={this.handleSwitchToWeekly}
            updateChartPrefs={this.updateChartPrefs}
            updateDatetimeLocation={this.updateDatetimeLocation} />
          );
        /* jshint ignore:end */
      case 'weekly':
        /* jshint ignore:start */
        return (
          <Weekly
            bgPrefs={this.state.bgPrefs}
            chartPrefs={this.state.chartPrefs}
            initialDatetimeLocation={this.state.initialDatetimeLocation}
            patientData={this.state.chartData}
            onSwitchToDaily={this.handleSwitchToDaily}
            onSwitchToSettings={this.handleSwitchToSettings}
            onSwitchToWeekly={this.handleSwitchToWeekly}
            updateChartPrefs={this.updateChartPrefs}
            updateDatetimeLocation={this.updateDatetimeLocation} />
          );
        /* jshint ignore:end */
      case 'settings':
        /* jshint ignore:start */
        return (
          <Settings
            bgPrefs={this.state.bgPrefs}
            chartPrefs={this.state.chartPrefs}
            patientData={this.state.chartData}
            onSwitchToDaily={this.handleSwitchToDaily}
            onSwitchToSettings={this.handleSwitchToSettings}
            onSwitchToWeekly={this.handleSwitchToWeekly} />
          );
        /* jshint ignore:end */
    }
  },
  // fetch & process
  fetchData: function() {
    this.log('Fetching data...');
    d3.json(dataUrl, this.processData);
  },
  processData: function(err, data) {
    this.log('Processing data...');
    if (err) {
      throw new Error('Could not fetch data file at ' + dataUrl);
    }
    console.time('Nurseshark Total');
    data = nurseshark.processData(data, this.state.chartPrefs.timePrefs).processedData;
    console.timeEnd('Nurseshark Total');
    this.updateData(data);
  },
  updateData: function(data) {
    console.time('TidelineData Total');
    var tidelineData = new TidelineData(data, {timePrefs: this.state.chartPrefs.timePrefs});
    console.timeEnd('TidelineData Total');
    window.tidelineData = tidelineData;
    this.setState({
      chartData: tidelineData,
      bgPrefs: {
        bgClasses: tidelineData.bgClasses,
        bgUnits: tidelineData.bgUnits
      },
      chartType: 'daily'
    });
  },
  // handlers
  handleSwitchToDaily: function(datetime) {
    this.setState({
      chartType: 'daily',
      initialDatetimeLocation: datetime || this.state.datetimeLocation
    });
  },
  handleSwitchToSettings: function() {
    this.setState({
      chartType: 'settings'
    });
  },
  handleSwitchToWeekly: function(datetime) {
    datetime = datetime || this.state.datetimeLocation;
    if (this.state.chartPrefs.timePrefs.timezoneAware) {
      datetime = dt.applyOffset(datetime, -dt.getOffset(datetime, this.state.chartPrefs.timePrefs.timezoneName));
    }
    this.setState({
      chartType: 'weekly',
      initialDatetimeLocation: datetime
    });
  },
  updateChartPrefs: function(newChartPrefs) {
    var currentPrefs = _.clone(this.state.chartPrefs);
    _.assign(currentPrefs, newChartPrefs);
    this.setState({
      chartPrefs: currentPrefs
    }, function() {
      // this.log('Global example state changed:', JSON.stringify(this.state));
    });
  },
  updateDatetimeLocation: function(datetime) {
    this.setState({
      datetimeLocation: datetime
    }, function() {
      // this.log('Global example state changed:', JSON.stringify(this.state));
    });
  }
});

React.renderComponent(
  /* jshint ignore:start */
  <Example/>,
  /* jshint ignore:end */
  document.body
);

@@ -4619,22 +4619,8 @@
 efs)
-.processedData
 ;%0A  
@@ -4671,20 +4671,235 @@
 his.
-updateData(d
+log(data.erroredData.length, 'items in the erroredData. :(', _.countBy(data.erroredData, 'type'));%0A    this.log('Unique error messages:', _.unique(_.pluck(data.erroredData, 'errorMessage')));%0A    this.updateData(data.processedD
 ata)

add some logging of what (if anything) is in the erroredData