const $ = require('jquery');
const _ = require('underscore');
const Backbone = require('backbone');
const request = require('request');
const { get, isEmpty } = require('lodash');
const { maybePluralize } = require('./utils');

const ByMeModel = Backbone.Model.extend({
  'initialize': function() {
    this.timerID = 0;
    // this.fsCollection = fsCollection;
    this.listenTo(this, 'change:llSix', this.onChange);
    this.listenTo(this, 'change:moving', this.onMoving);
  },
  'onMoving': function() {
    console.log('>> onMoving', this);
  },
  'onChange': function() {
    // this.getByMe(); trigger when not moved for 30 seconds
    if (this.get('atHomeOrWork') !== true)
      this.timerID = setTimeout(
        () => this.getByMe(),
        30000
      );
    else {
      clearInterval(this.timerID);
      console.log('>> ByMe: atHomeOrWork');
    }
  },
  'getByMe': function() {
    const llSix = this.get('llFixed');

    // const section = (partOfDay >= 11 && partOfDay <= 14) ? 'food' : 'topPicks';
    request({
      'url': `${window.loc}/rightbyme`,
      'method': 'GET',
      'qs': {
        'll': llSix
      }
    }, function(err, res, body) {
      if (err)
        console.error(err);
      else {
        // console.log(body);

        const fsJSON = JSON.parse(body);

        // console.log(fsJSON);

        this.set('byme', fsJSON);
      }
    }.bind(this));
  }
});

const ByMeView = Backbone.View.extend({
  'id':'byme',
  'className': '',
  'template': _.template('<div></div>'),
  'yelpTemplate': _.template(`<div id="bymeYelp" class="itemRow">
<div class="mui-col-md-4 mui-col-xs-4">
<img src="gfx/stars_<%= yelp.rating * 10 %>.png">
</div>
<div class="mui-col-md-4 mui-col-xs-4 mui--text-center">
<%= yelp.reviewCount %> review
</div>
<div class="mui-col-md-4 mui-col-xs-4 mui--text-right">
<img src="gfx/yssdk_yelp_logo.png">
</div>
</div>
  `),
  'tipsTemplate': _.template(`
  <div id='bymeTips'>
  <div class="mui--text-subhead">Tips</div>
  <div  class='scrolling-wrapper-flexbox' style="height: 100px;">
      <%_.forEach(tips, function(i) {%>
      <div class="scrollCardHalf mui--text-body1">
              <%=i %>
          </div>
      <%}) %>
    </div>
  </div>  
  `),
  'imagesTemplate': _.template(`
    <div id='bymeImages'>
    <div  class='scrolling-wrapper-flexbox' style="height: 100%;">
        <%_.forEach(images, function(i) {%>
        <div class="imageCard">
        <img src="<%=i %>" class="scrollImg">
        </div>
        <%}) %>
      </div>
    </div>  
    `),
  'initialize': function(options) {
    this.eventBus = options.eventBus;
    this.location = options.location;

    // this.model.bind('change', this.render, this);
    this.location.bind('change', this.updateLocation, this);
    this.location.bind('change:atHomeOrWork', this.atHomeOrWork, this);
    this.model.bind('change:byme', this.render, this);
  },
  'events': {
    'click .itemRow': 'doClick'
  },
  'atHomeOrWork': function(m) {
    console.log('>> atHomeOrWork', m);
  },
  'updateLocation': function(l) {
    console.log('>> ByMe Location has changed...');

    if (l.has('location')) {
      const location = l.get('location');
      if (location.hasOwnProperty('atHomeOrWork')) {
        this.model.set(location);

        if (location.atHomeOrWork)
          // We're at home so hide
          this.$el.parent().hide();
      }
    }
    else
      console.log('>> ByMe No location yet');
  },
  'render': function() {
    console.log('>> ByMe render');
    // console.log(this.model);

    // console.log(this.model);
    const contents = [];
    const m = this.model.get('byme');
    // this.imagesTemplate(this.model.toJSON()), this.yelpTemplate(this.model.toJSON()), this.tipsTemplate(this.model.toJSON())

    if (!isEmpty(m.images))
      contents.push(this.imagesTemplate(m));

    if (!isEmpty(m.yelp))
      contents.push(this.yelpTemplate(m));

    if (!isEmpty(m.tips))
      contents.push(this.tipsTemplate(m));

    this.$el.html(contents.join(''));
    // console.log(this.el);
    this.$el.parent().children('#byMeTitle').html(m.name);
    this.$el.parent().show();
  }

});

module.exports = { ByMeModel, ByMeView };
