//recoge la alarma lanzada
navigator.mozSetMessageHandler("alarm", function (mozAlarm) { 

    if( mozAlarm.data.type == 'daily' ){
      localStorage.btnDailyStatus = 1;
    }
    else if( mozAlarm.data.type == 'answer' ){
      localStorage.btnAnswerStatus = 2;
      localStorage.dailyAlarm = JSON.stringify( getRandomDaily() );
    }
    else if ( mozAlarm.data.type == 'review' ){
      localStorage.counterReviewAlarm = parseInt(localStorage.counterReviewAlarm)+1;
    }
    
    sendNotification(mozAlarm.data.title, mozAlarm.data.options);
    //window.location.reload();
     
});

//alarma para daly, answer y review 
function randomMomentTomorrow(){
    
    var data = {
        'title': 'Your Daily',
        'type': 'daily',
        'options': {
          'body':'Our teacher is waiting for you',
          'icon':'http://dailyexpression.hol.es/wp-content/uploads/2013/11/dailyExpressionFavicon.png',
          'type': 'daily'
      }
    }

    var dataAnswer = {
        'title': 'Put in practice',
        'type': 'answer',
        'options': {
          'body':'Our demanding teacher wants to test you',
          'icon':'http://dailyexpression.hol.es/wp-content/uploads/2013/11/dailyExpressionFavicon.png',
          'type': 'answer'
      }
    }
    //random number between the 9:00 to 22:00
    var hour = Math.floor(Math.random() * (22 - 9 + 1)) + 9;
    //random number between the befor hour to 23:00
    var hourAnswer = Math.floor(Math.random() * (23 - (hour+1) + 1)) + (hour+1);
    var minute = Math.floor(Math.random() * 59) + 1;

    var today = new Date();
    var tomorrow = new Date();
    tomorrow.setDate(today.getDate()+1);
    
    tomorrow.setHours(hour);
    tomorrow.setMinutes(minute);

    if( howMany() > 0 )addAlarm(tomorrow, data);
      tomorrow.setHours(hourAnswer);
    if( howMany() > 0 )addAlarm(tomorrow, dataAnswer);
    
}

function randomMomentRegister(){
    
    var data = {
        'title': 'Your Daily',
        'type': 'daily',
        'options': {
          'body':'Our teacher is waiting for you',
          'icon':'http://dailyexpression.hol.es/wp-content/uploads/2013/11/dailyExpressionFavicon.png',
          'type': 'daily'
      }
    }

    var dataAnswer = {
        'title': 'Put in practice',
        'type': 'answer',
        'options': {
          'body':'Our demanding teacher wants to test you',
          'icon':'http://dailyexpression.hol.es/wp-content/uploads/2013/11/dailyExpressionFavicon.png',
          'type': 'answer'
      }
    }
    var today = new Date();
    today.setMinutes( today.getMinutes()+5 );
    addAlarm(today, data );

    today.setMinutes(today.getMinutes()+10 );
    addAlarm(today, dataAnswer);
}

//programa la alarm review. Necesita siempre comprobar si hay dailies para revisar
//pueden programarse un máximo de 4, cuando ya tienes todos los dailies pasados  
function alarmReview(){

  var requests = navigator.mozAlarms.getAll();
  
  requests.onsuccess = function () {
   
    var dailiesToReview = getDailiesToReview();

    var countReviewAlarm = 0;
    for(var i = 0; i < this.result.length; i++){
      if( this.result[i].data.type == 'review' ){
        countReviewAlarm++;
      }
    }
    

    if( dailiesToReview.length > 0 && dailiesToReview.length > countReviewAlarm && this.result.length < 3 && parseInt(localStorage.counterReviewAlarm) < dailiesToReview.length ) {
      var data = {
          'title': 'Review',
          'type': 'review',
          'options': {
            'body':'Have you studied? It\'s time to test you',
            'icon':'http://dailyexpression.hol.es/wp-content/uploads/2013/11/dailyExpressionFavicon.png',
            'type': 'answer'
        }
      }
      //random number between the 9:00 to 22:00
      var hour = Math.floor(Math.random() * (22 - 9 + 1)) + 9;
      var minute = Math.floor(Math.random() * 59) + 1;
      var today = new Date();
      var tomorrow = new Date();
      tomorrow.setDate(today.getDate()+1);
      tomorrow.setHours(hour);
      tomorrow.setMinutes(minute);

      addAlarm(tomorrow, data);
      
    }
   
  };

}

function alarmValidateEmail( days ){
    
    var data = {
        'title': 'Email validation',
        'type': 'validate',
        'options': {
          'body':'Check your email and validate it or your account will be removed',
          'icon':'http://dailyexpression.hol.es/wp-content/uploads/2013/11/dailyExpressionFavicon.png',
          'type': 'validate'
      }
    }
    var today = new Date();
    var dateValidateAlarm = new Date();
    dateValidateAlarm.setDate( today.getDate()+days);
    
    addAlarm( dateValidateAlarm, data );
    
}

//Función que añade alarmas. Es utilizado por las funciones anteriorres.
function addAlarm(date, data){

  // La cadena "ignoreTimezone" es lo que hace a la alarma ignorar esto
  var request = navigator.mozAlarms.add(date, "honorTimezone", data);

  var type = 'Tipo: '+data.type+' - '+data.options.type;

  request.onsuccess = function () {
    console.log("La alarma ha sido programada. "+type);
    
  };

  request.onerror = function () { 
    console.log("Ha ocurrido un error: " + this.error.name);
  };
}

//solo para testeo
//añade alarmas para hoy
//borrar
function addAlarmToday(hour, minute, data){
  var today = new Date();
  var tomorrow = new Date();
  tomorrow.setDate(today.getDate());
  var myDate = tomorrow;
  
  myDate.setHours(hour);
  myDate.setMinutes(minute);
  myDate.setSeconds(00);


  // La cadena "ignoreTimezone" es lo que hace a la alarma ignorar esto
  var request = navigator.mozAlarms.add(myDate, "honorTimezone", data);

  request.onsuccess = function () {
    console.log("La alarma ha sido programada");
  };

  request.onerror = function () { 
    consle.log("Ha ocurrido un error: " + this.error.name);
  };
}


//Elimina alarmas por tipo
function removeAlarmByType(type){
  
  var requests = navigator.mozAlarms.getAll();
  
  requests.onsuccess = function () {
    this.result.forEach(function (alarm) {
      // Later on, removing the alarm if it exists
      if (alarm.data.type == type) {
        navigator.mozAlarms.remove(alarm.id);
        showAlarmsSaved();
      }
    });
    
  };

}

//remove one by type
function removeOneAlarmByType(type){
  
  var requests = navigator.mozAlarms.getAll();
  
  requests.onsuccess = function () {
    this.result.forEach(function (alarm) {
      // Later on, removing the alarm if it exists
      if (alarm.data.type == type) {
        navigator.mozAlarms.remove(alarm.id);
        return true;
      }
    });
    
  };

}

//borra todas las alarmas
function removeAlarmAll(){
  var requests = navigator.mozAlarms.getAll();
  
  requests.onsuccess = function () {
    this.result.forEach(function (alarm) {
        navigator.mozAlarms.remove(alarm.id);   
    }); 
  };

}

// remove if is the same type and today date
function removeAlarmByTypeAndDate(type, date){
  // Esta es la fecha a programar la alarma
  var requests = navigator.mozAlarms.getAll();
  
  requests.onsuccess = function () {
    this.result.forEach(function (alarm) {
  
      if (alarm.data.type == type && 
        alarm.date.getDate() == date.getDate() &&
        alarm.date.getMonth() == date.getMonth() &&
        alarm.date.getFullYear() == date.getFullYear()
      ) {
        navigator.mozAlarms.remove(alarm.id);
        console.log('Deleted auto getDaily');
      }
    });
    
  };

}

//solo para testeo
//borrar
function showAlarmsSaved(){
  var requests = navigator.mozAlarms.getAll();
  
  requests.onsuccess = function () {
    var html = '<ul>';
    this.result.forEach(function (alarm) {
      html += '<li><ul>';
      //html += '<li>Id: ' +alarm.id+'</li>';
      html += '<li>date: ' + alarm.date+'</li>';
      //html += '<li>respectTimezone: ' + alarm.respectTimezone +'</li>';
      //html += '<li>data: ' + JSON.stringify(alarm.data)+'</li>';
      html += '<li>Type: ' + JSON.stringify(alarm.data.type)+'</li>';
      html += '<li>Options type: ' + JSON.stringify(alarm.data.options.type)+'</li>';
      //html += '<li> <button id="'+alarm.id+'" class="delete_alarm">Delete</button> </li>';
      html += '</ul></li>';
    });
    printAlarmsSaved(html);
    //console.log(html);
  };

  requests.onerror = function () { 
    console.log("An error occurred: " + this.error.name);
  };
}

//solo para testeo
//borrar
function printAlarmsSaved(html){
  $('#div_show_all_allarms').html(html);
}

