/**
 * Created by marti on 29/02/2016.
 */


(function() {

  var storedData;
  var weatherCount = 0;
  var skycons = new Skycons({"color": "white"});
  var refreshTimer = 0;
  var viewTimer = 0;
  var eventBus = {};

  MicroEvent.mixin(eventBus);

  function getData() {
    $.ajax({
      type: 'GET',
      url: '/today/data',
      data: '',
      dataType: 'json',
      timeout: 10000,
      context: $('body'),
      contentType: ('application/json'),
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type'
      },
      success: function(data) {
        console.log(data);
        storedData = data;
       // startWeather();
        updateWeather();
      },
      error: function(xhr, type) {
        console.log("ajax error");
        console.log(xhr);
        console.log(type);
      }
    });
  }

  function updateWeather() {
    $('#wCtext').empty().html(storedData.data.weather.currently);
    $('#wLtext').empty().html(storedData.data.weather.later);
    $('#wTtext').empty().html(storedData.data.weather.today);
    // $('#wDaily').empty();

    for (var t = 0; t < storedData.data.weather.data.daily.data.length; t++) {
      var m = 'icon' + (t + 1).toString();
      var d = '#d' + (t + 1).toString();
      var ts = parseInt(storedData.data.weather.data.daily.data[t].time) * 1000;
      var n = Date.create(ts).format('{weekday}');

      skycons.add(m, storedData.data.weather.data.daily.data[t].icon);
      $(d).empty().html(n);
    }
    skycons.play();

    $('#wLater').hide();
    $('#wToday').hide();
    $('#wDaily').hide();
  }

  function switchWeather() {

    weatherCount++;
    weatherCount = weatherCount < 4 ? weatherCount : 0;

    $('#wCurrent').toggle(weatherCount == 0);
    $('#wLater').toggle(weatherCount == 1);
    $('#wToday').toggle(weatherCount == 2);
    $('#wDaily').toggle(weatherCount == 3);

  }

  // event bus

  eventBus.bind('switchWeather', function() {
    switchWeather();
  });

  // timers
  function refreshWeatherView() {
    eventBus.trigger('switchWeather');
    var now = new Date();
       var mod = 10000 - (now.getTime() % 10000);

       viewTimer = setTimeout(function() {refreshWeatherView();}, mod + 10);

  }

  function updateClock() {
    var n = Date.create(new Date()).format('{HH}:{mm}');
    $('#clockDisplay').html(n);
  }

  function clock() {
    'use strict';
    updateClock();
    var now = new Date();
    var mod = 60000 - (now.getTime() % 60000);

    setTimeout(function() {clock();}, mod + 10);

  }

  function refresh() {
    getData();
    var now = new Date();
    var mod = 600000 - (now.getTime() % 600000);

    refreshTimer = setTimeout(function() {refresh();}, mod + 10);

  }

  clock();
//  getData();
  refresh();
  refreshWeatherView();
  $('#misc').html($(window).width());

})();

