const $ = require('jquery');
const _ = require('underscore');
const Backbone = require('backbone');
const request = require('request');
const { get } = require('lodash');
const { reduceNearby } = require('./reducers');
const { toHour } = require('./utils');

const { FSDetailView } = require('./Foursquare');

// console.notificationsTitle = 'Nearby';

const fsItem = Backbone.Model.extend({

});

const FSCollection = Backbone.Collection.extend({
  'model': fsItem
});

const fsCollection = new FSCollection();

const fsItemView = Backbone.View.extend({
  'tagName': 'div',
  'className': 'itemRow mui--align-middle',
  'template': _.template(`
<span class="mui--text-dark mui--text-subhead"><%= name %></span> <span class="mui--text-caption mui--text-dark-secondary"><%= category %></span>      `),
  'initialize': function() {
    this.render();
  },
  'attributes': function() {
    return {
      'data-id': this.model.id
    };
  },

  'render': function() {
    this.$el.html(this.template(this.model.toJSON()));
  }
});

const NearbyModel = Backbone.Model.extend({
  'initialize': function() {
    this.fsCollection = fsCollection;
    this.timerID = 0;
    this.tick();
    this.set('totalResults', 0);
    this.listenTo(this, 'change:llFixed change:section', this.onChange);
  },
  'tick': function() {
    const hour = parseInt((new Date()).getHours().toString(), 10);
    const section = (hour >= 11 && hour <= 14) ? 'food' : 'topPicks';

    this.set('section', section);

    this.timerID = setTimeout(
      () => this.tick(),
      toHour()
    );
  },
  'onChange': function() {
    this.getNearby();
  },
  'getNearby': function() {
    const llFixed = this.get('llFixed');

    const hour = parseInt((new Date()).getHours().toString(), 10);
    const section = this.get('section');
    console.log('>> Nearby section:', hour, section);
    request({
      'url': `${window.loc}/fsexplore`,
      'method': 'GET',
      'qs': {
        'll': llFixed,
        'section': section
      }
    }, function(err, res, body) {
      if (err)
        console.error(err);
      else {
        const fsJSON = JSON.parse(body);
        const groups = get(fsJSON, 'response.groups');
        const items = groups[0].items;
        const newItems = [];
        this.set('totalResults', get(fsJSON, 'response.totalResults'));
        for(const item of items)
          newItems.push(reduceNearby(item));

        this.fsCollection.reset(newItems);
      }
    }.bind(this));
  }
});

const NearbyView = Backbone.View.extend({
  'id':'nearby',
  'className': '',
  'initialize': function(options) {
    this.eventBus = options.eventBus;
    this.location = options.location;
    this.fsCollection = fsCollection;

    // this.model.bind('change', this.render, this);
    this.location.bind('change', this.updateLocation, this);

    this.$nearby = $('#nearby');

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

    this.fsCollection.bind('reset', this.render, this);
  },
  'events': {
    'click .itemRow': 'doClick'
  },
  'updateLocation': function(l) {
    console.log('>> Nearby Location has changed...');

    if (l.has('location')) {
      const location = l.get('location');
      if (location.hasOwnProperty('atHome'))
        this.model.set(location);
    }
    else
      console.log('>> Nearby No location yet');
  },
  'blah': function() {
    console.log('nearby render');
  },
  'render': function() {
    console.log('Nearby:Render');
    const totalResults = this.model.get('totalResults');
    console.log('>> totalResults', totalResults);
    this.$el.empty();
    this.fsCollection.each(function(item) {
      const fsView = new fsItemView({ 'model': item });
      this.$el.append(fsView.el);
      // this.$el.append(personView.el); // adding all the person objects.
    }, this);

    if (totalResults > 0)
      this.$el.parent().show();
    else
      this.$el.parent().hide();
  },
  'doClick': function(d) {
    console.log('Do click', d);
    const id = get(d, 'currentTarget.dataset.id', '');
    console.log(id);

    const fsdetail = new FSDetailView({ 'fsID':id });
  }

});

module.exports = { NearbyModel, NearbyView };
// 55.949443, -4.570721;
