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

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({
  'defaults' : function (obj) {
    // return a new object
    return {
      'update' : new Date().getTime()
    };
  }, 'initialize': function() {
    this.fsCollection = fsCollection;
    this.timerID = 0;
    this.tick();
    this.set('totalResults', 0);
    this.listenTo(this, 'change:llFixed change:section change:update', 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);
    console.info('>> Nearby:request');
    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);
        this.logUpdate();
      }
    }.bind(this));
  }, 'logUpdate': function() {
    console.log('Nearby logging:');

    const time = new Date().getTime() ;

    this.set('time', time);
  }
});

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:llFixed', this.updateLocation, this);

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

    this.fsCollection.bind('reset', this.render, this);
    this.eventBus.on('focused', this.focused, this);

    this.other = $('<div id="nearbyOther" class="cardLink"><i class="seemore material-icons mui--align-middle " >arrow_forward</i> <span class="seemore mui--align-middle">Other locations</span></div>');
  },
  'events': {
    'click .itemRow': 'doClick'
  },
  'updateLocation': function(l) {
    console.log('>> Nearby Location has changed...');

    if (l.has('atHome')) {
      const llFixed = l.get('llFixed');
      this.model.set('llFixed', llFixed);
    }
    else
      console.log('>> Nearby No location yet');
  },
  'blah': function() {
    console.log('nearby render');
  },
  'render': function() {
    console.info('>> 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);

    this.$el.append(this.other);
    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 });
  }, 'focused': function() {
    console.log('>> Nearby received focus msg');
    const now = new Date().getTime();
    const since = now - this.model.get('time');

    console.log(`Nearby was last updated: ${TimeFormat.fromMs(since, 'hh:mm')} ago`);

     if (since > (60 * 1000 * 60) )
      this.model.set('update', now);
  }

});

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