/**
 * Created by Martin on 15/03/2016.
 */
"use strict";

var APP = function () {
  var refreshStep = 0,
    preUrl = 'https://pipes.silvrtree.co.uk/',

    _storage = {
      lastupdated: null,
      feeds: {}
    },
    _list = null,
    _feed = null,

    feeds = ['paleo', 'lifestyle', 'tech', 'news', 'fit', 'bored', 'jobs-special'],

    lastUpdated = null,
    preCache = function () {
      _list = new EJS({url: 'ejs/list.ejs'});
      _feed = new EJS({
        url: 'ejs/testcards.ejs'
      });
    },
    getLastUpdateDate = function () {
      var formatted, dt;
      // this.lastUpdated = localStorage.getItem('lastUpdated') || null;

      if (lastUpdated === null) {
        $('#lastupdate').empty().append('Never');
      }
      else {
        dt = new Date(lastUpdated);
        formatted = moment(dt).startOf('minute').fromNow();
        console.log(formatted);
        $('#lastupdate').empty().append(formatted);
      }

    },
    doSave = function () {
      console.log('Saving...');
      lastUpdated = new Date();
      _storage.lastupdated = lastUpdated;
      localStorage.setItem('lastUpdated', lastUpdated);
      localStorage.setItem('_storage', JSON.stringify(_storage));
      getLastUpdateDate();
      // $.zprogress.done(true);
    },

    doRefresh = function () {
      var self = this;
      if (refreshStep < feeds.length) {
        var feedUrl = preUrl + feeds[refreshStep] + '.json';
        $('#lastupdate').empty().append('Refreshing: ' + feeds[refreshStep]);
        $.getJSON(feedUrl, function (data) {
         // console.log(self);

          doUpdate(data);
        });
      } else {
        console.log('Done');
        // $.zprogress.inc(0.2);
        doSave();
      }
    },
    showFeed = function (opt) {
      var output, d, $bodyContents ;
      $bodyContents = $('#bodyContents');
      console.log('show feed ' + opt);
      // $('#feedcontent').empty();
      d = {
        d: _storage.feeds[opt]
      };
      output = _feed.render(d);

      $bodyContents.empty();
      $('BODY').scrollTop(0);
      $bodyContents.html(output);

      $('img').unveil();
    },
    doUpdate = function (data) {
      console.log(this);
      console.log(data);
      _storage.feeds[feeds[refreshStep]] = data;

      console.log(_storage);
      refreshStep++;
      // $.zprogress.inc(0.2);
      doRefresh();
    },
    showList = function () {
      var key, output, d = {},
        list = [];
      for (key in _storage.feeds) {
        console.log(key);
        list.push({
          name: key
        });
      }

      d.list = list;

      output = _list.render(d);
      $('#listContainer').empty().html(output);

      for (key in _storage.feeds) {
        $('#' + key).on('click', $.proxy(showFeed, this, key));
      }

    },
    doLoad = function () {

      var _load = localStorage.getItem('_storage');
      $('#lastupdate').empty().append('Loading...');
      if (_load !== null) {
        _storage = JSON.parse(_load);
      }

      else {
        _storage = {
          lastupdated: null,
          feeds: {}
        };
      }

      lastUpdated = _storage.lastupdated || null;
      showList();
    },

    refresh = function () {
      refreshStep = 0;
      console.log('refresh');
      console.log(this);
      console.log('get ' + feeds[refreshStep]);
      $('#lastupdate').empty().append('Refreshing...');
      // $.zprogress.start();
      doRefresh();

    }, init = function () {
      $('#fnRefresh').on('click', $.proxy(refresh, this));
      console.log('app starting...');
      preCache();
      doLoad();
      getLastUpdateDate();
      console.log('Last updated: ' + lastUpdated);
    } ;

  $('#fnRefresh').on('click', function () {
    doLoad();
  });

  init();
};

MicroEvent.mixin(APP);

var app = new APP();


