const $ = require('jquery');
const _ = require('underscore');
const Backbone = require('backbone');
const request = require('request');
const { get, isEmpty } = require('lodash');
const { createPanel, addPanel } = require('./libs/panel');

const ForecastModel = Backbone.Model.extend({
  'defaults': function (obj) {
    // return a new object
    return {
      'update': new Date().getTime(),
      'last': new Date().getTime()
    };
  },
  'initialize': function() {
    this.listenTo(this, 'change:ll', this.onChange);
    this.listenTo(this, 'change:update', this.onChange);
  },
  'onChange': function() {
    console.log('>> LL changed:', this.get('ll'));
    this.getForecast();
  },
  'getForecast': function() {
    const ll = this.get('ll');
    request({
      'url': `${window.loc}/forecast`,
      'method': 'GET',
      'qs': {
        'll': ll
      }
    }, function(err, res, body) {
      if (err)
        console.error(err);
      else{
        // console.log(body);
        const fsJSON = JSON.parse(body);
        // console.log(fsJSON);
        fsJSON.last = new Date().getTime();
        this.set(fsJSON);
        // console.log(body);
      }
    }.bind(this));
  }

});

const ForecastView = Backbone.View.extend({
  'initialize': function(options) {
    this.eventBus = options.eventBus;

    /* this.model.on('all', function(eventName) {
      console.log(`${eventName } was triggered!`);
    });*/

    this.model.bind('change:time', this.doRender, this);
    this.eventBus.on('showForecast', this.showForecastPanel, this);
  },

  'templateCurrently': _.template(`
  <div class="forecastCurrently mui-panel glassy">
        <div class="mui--text-title"><i class="medium wi wi-forecast-io-<%= icon %>"></i> <%=summary%></div>
        <div>
        <i class="small material-icons mui--align-middle " >vertical_align_top</i><%=tempMax%>°
        <i class="small material-icons mui--align-middle " >vertical_align_bottom</i><%=tempMin%>°
        </div>
        <div class="large temp<%=~~(temperature) %>"><%=temperature%>°</div>
  </div>
        `),
  'templateForecast': _.template(`
  <div class="forecastToday mui-panel glassy">
  <h3>Forecast</h3>
  <div  class='scrolling-wrapper-flexbox hourly' style="height: 100px;">
          <%_.forEach(today, function(i) {%>
          <div class="hourlyCard">
                 <div class="mui--text-center"><%=i.time %></div>
                 <div class="mui--text-center"><i class="small wi wi-forecast-io-<%= i.icon %>"></i></div>
                 <div class="mui--text-center temp<%=~~(i.temp) normalWeight%>"><%=~~(i.temp)%>°</div>
              </div>
          <%}) %>
        </div>
  
  <div>
  <div class="dailyCard">
  <%_.forEach(daily, function(i) {%>
            <div class="mui-row">
                   <div class="mui-col-xs-6 mui--text-left mui--text-title"><%=i.time %></div>
                   <div class="mui-col-xs-2 mui--text-center"><i class="mui--text-title wi wi-forecast-io-<%= i.icon %>"></i></div>
                   <div class="mui-col-xs-2 mui--text-center temp<%=~~(i.tempHigh) %> mui--text-title "><%=~~(i.tempHigh)%>°</div>
                   <div class="mui-col-xs-2 mui--text-center temp<%=~~(i.tempLow) %> mui--text-title"><%=~~(i.tempLow)%>°</div>
                </div>
            <%}) %>
  </div>
  
</div>
  </div>
  `),
  'templateDetails': _.template(`
  <div class="forecastDetails mui-panel glassy">
  <h3>Details</h3>
  <div class="mui-row">
        <div class="mui-col-xs-6 mui--text-left mui--text-body2">Humidity</div>
        <div class="mui-col-xs-6 mui--text-right mui--text-title"><%=~~(humidity * 100) %>%</div>
  </div>
  <div class="mui-row">
        <div class="mui-col-xs-6 mui--text-left mui--text-body2">Visibility</div>
        <div class="mui-col-xs-6 mui--text-right mui--text-title"><%=visibility %><span class="mui--text-body1">km</span></div>
  </div>
  <div class="mui-row">
        <div class="mui-col-xs-6 mui--text-left mui--text-body2">UV Index</div>
        <div class="mui-col-xs-6 mui--text-right mui--text-title"><%=uvIndex %></div>
  </div>
<div class="mui-row">
        <div class="mui-col-xs-12 mui--text-left mui--text-body1"><%=summary%></div>
  </div>
  <h3>Wind & Pressure</h3>
<div class="mui-row">
        <div class="mui-col-xs-3 mui--text-left mui--text-body2">Wind</div>
        <div class="mui-col-xs-3 mui--text-right mui--text-title"><%=windSpeed %><span class="mui--text-body1">km/h</span></div>
        <div class="mui-col-xs-3 mui--text-left mui--text-body2">Barometer</div>
        <div class="mui-col-xs-3 mui--text-right mui--text-title"><%=pressure %><span class="mui--text-body1">mBar</span></div>
        
  </div>
<h3>Sun & Moon</h3>
  <div class="mui-row">
            <div class="mui-col-xs-3 mui--text-left mui--text-body2">Sunrise</div>
            <div class="mui-col-xs-3 mui--text-right mui--text-title"><%=sunriseTime %></div>
            <div class="mui-col-xs-3 mui--text-left mui--text-body2">Sunset</div>
            <div class="mui-col-xs-3 mui--text-right mui--text-title"><%=sunsetTime %></div>
            
      </div>
      
  </div>
    `),

  'showForecastPanel': function(ll) {
    console.log('Showing forecast', ll);
    const prevll = this.model.get('ll');
    const lastTime = this.model.get('last');
    const now = new Date().getTime();

    // (60 * 1000 * 60)
    const hour = (new Date()).getHours();
    this.model.set('ll', ll);

    this.$newPanel = createPanel({ 'title':'Weather forecast', 'divId':'weatherP' });

    this.$el = addPanel(this.$newPanel);
    this.$el.addClass('animTrans');

    if (hour >= 6 && hour < 18 )
      this.$el.addClass('weatherDay');
    else
      this.$el.addClass('weatherEvening');

    this.$el.empty();
    this.$newPanel.show();

    console.log(this.model);
    if (prevll === ll)
      if (now > lastTime + (60 * 1000 * 60)) {
        this.model.set('update', now);
      }
      else {
        this.doRender();
      }
  },
  'events': {
    'click .closebutton': 'doClick'
  },
  'doClick': function(d) {
    console.log('Do click', d);
    const id = get(d, 'currentTarget', '');
    console.log(id);
    // this.eventBus.trigger('showNews', id);
  },
  'doClose': function(d) {
    console.log('close??');
  },
  'doRender': function() {
    // this.$el.html(this.template(this.model.get('article')));
    console.log('ForecastView::doRender');
    const html = [];

    const currently = this.model.get('currently');
    const forcastToday = { 'today':this.model.get('forcastToday'), 'daily':this.model.get('dailyForecast') };
    const details = this.model.get('details');
html.push('<div class="mui-container">');
    html.push(this.templateCurrently(currently));
    html.push(this.templateForecast(forcastToday));
    html.push(this.templateDetails(details));
    html.push('</div>');
    html.push('<div class="endbumper"></div>');

    this.$el.addClass(this.backgroundGen(currently.icon));

    this.$el.html(html.join(''));
  },
  'backgroundGen': function(icon) {
    const hour = (new Date()).getHours();
    const suffix = (hour >= 6 && hour < 18 ) ? '_d' : '_n';
    let output = '';
    switch (icon) {

      case 'clear':
        output = `clear${suffix}`;
        break;
      case 'clear-day':
        output = 'clear_d';
        break;
      case 'clear-night':
        output = 'clear_n';
        break;
      case 'rain':
        output = `rain${suffix}`;
        break;
      case 'snow':
      case 'sleet':
      case 'hail':
        output = `snow${suffix}`;
        break;
      case 'fog':
        output = `foggy${suffix}`;
        break;
      case 'wind':
      case 'cloudy':
        output = `cloudy${suffix}`;
        break;
      case 'partly-cloudy-day':
        output = 'cloudy_d';
        break;
      case 'partly-cloudy-night':
        output = 'cloudy_n';
        break;

      case 'thunderstorm':
      case 'tornado':
        output = `storm${suffix}`;
        break;

      default:
        console.log(`Sorry, we are out of ${ icon }.`);

    }

    return output;
  }

});

module.exports = { ForecastModel, ForecastView };

