const $ = require('jquery');
const _ = require('underscore');
const Backbone = require('backbone');
const request = require('request');
const { get, isEmpty } = require('lodash');
const { maybePluralize } = require('./libs/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
    console.log('>> changedAttributes:', this.changedAttributes());
    if (this.get('atHomeOrWork') !== true) {
      if ( this.timerID === 0) {
        console.log('setting timeout....');
        clearInterval(this.timerID);
        this.timerID = setTimeout(
          () => this.getByMe(),
          30000
        );
      }
    }
    else {
      clearInterval(this.timerID);
      console.log('>> ByMe: atHomeOrWork');
    }
  },
  'getByMe': function() {
    const ll = this.get('ll');

    console.info('>> ByMe:request');

    clearInterval(this.timerID);
    this.timerID = 0;

    console.log(this.toJSON());
    // const section = (partOfDay >= 11 && partOfDay <= 14) ? 'food' : 'topPicks';
    request({
      'url': `${window.loc}/rightbyme`,
      '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);

        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-body2">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>  
    `),
  'tweetsTemplate': _.template(`
    <div id='bymeTweets'>
    <div class="mui--text-body2">Tweets</div>
    <div  class='scrolling-wrapper-flexbox' style="height: 100px;">
        <%_.forEach(tweets, function(i) {%>
        <div class="scrollCardHalf mui--text-body1">
                <%=i %>
            </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:llSix', 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) {
    const atHomeOrWork = m.get('atHomeOrWork');
    console.log('>> atHomeOrWork', atHomeOrWork);
    if (atHomeOrWork)
    // We're at home so hide
      this.$el.parent().hide();
  },
  'updateLocation': function(l) {
    console.log('>> ByMe Location has changed...');

    if (l.has('atHome')) {
      const llSix = l.get('llSix');
      const ll = l.get('ll');
      const atHomeOrWork = l.get('atHomeOrWork');
      this.model.set({ llSix, atHomeOrWork, ll });
      if (atHomeOrWork)
      // We're at home so hide
        this.$el.parent().hide();
    }

    else
      console.log('>> ByMe No location yet');
  },
  'render': function() {
    console.info('>> 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));

    if (!isEmpty(m.tweets))
      contents.push(this.tweetsTemplate(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 };
