
var bagList = Array();

function getBagList(callback)
{
  var service = new ROSLIB.Service({
    ros : ros,
    name : '/aescape/bags/getBagList',
    serviceType : 'demobot/TriggerList'
  });
  
  var request = new ROSLIB.ServiceRequest({});
  
  service.callService(request, function(result) {
    callback(JSON.parse(result.message));
  });
}

function getBagCategoryList(callback)
{
  var service = new ROSLIB.Service({
    ros : ros,
    name : '/aescape/bags/getCategoryList',
    serviceType : 'demobot/TriggerList'
  });
  
  var request = new ROSLIB.ServiceRequest({});
  
  service.callService(request, function(result) {
    callback(JSON.parse(result.message));
  });
}

function getBagTagList(callback)
{
  var service = new ROSLIB.Service({
    ros : ros,
    name : '/aescape/bags/getTagList',
    serviceType : 'demobot/TriggerList'
  });
  
  var request = new ROSLIB.ServiceRequest({});
  
  service.callService(request, function(result) {
    callback(JSON.parse(result.message));
  });
}


setTimeout(function(){
  document.querySelector('.hand-panel-right .status-bar').style.height = document.querySelector('.hand-panel-left .status-bar').offsetHeight + 20 + "px";
  $(function () {
    $('[data-toggle="popover"]').popover()
  })
}, 100);



function displayTaggingOptions(mode) {

  var modeTag = '#' + mode + 'Tags';
  var fileNameSelector = '#' + mode + 'BagFileName';
  var categorySelector = '#' + mode + 'BagCategory';
  var tagSelector = '#' + mode + 'BagTags';

  //Subscribe to topics from the backend which indicate recording or playback is complete
  document.querySelector(modeTag).classList.add('open');
  //Putting this in a timeout to wait for the animation to finish completing
  setTimeout(function(){
    document.querySelector(modeTag).style.overflow = "visible";
  }, 600)

  var $fileNameSelect = $(fileNameSelector).selectize({
    valueField: 'name',
    labelField: 'name',
    searchField: ['name'],
    options: [], 
    create: true,
    placeholder : "Enter a name for the bag"
  });  

  var fileNameSelectize = $fileNameSelect[0].selectize;
  fileNameSelectize.clearOptions()
  // /aescape/bags/getBagList
  getBagList(function(results){
    fileNameSelectize.addOption(results.map(function(bagName){
      return {name : bagName}
    }));
  })

  var $categoryNameSelect = $(categorySelector).selectize({
    valueField: 'name',
    labelField: 'name',
    searchField: ['name'],
    options: [], 
    create: true,
    placeholder : "Enter or select a category for the bag"
  });  

  var categoryNameSelectize = $categoryNameSelect[0].selectize;
  categoryNameSelectize.clearOptions()
  getBagCategoryList(function(results){
    categoryNameSelectize.addOption(results.map(function(bagName){
      return {name : bagName}
    }));
  })

  var $tagSelect = $(tagSelector).selectize({
    valueField: 'name',
    labelField: 'name',
    searchField: ['name'],
    maxItems: 20, 
    options: [], 
    create: true,
    placeholder : "Enter or select tags for the bag"
  });  

  var tagSelectize = $tagSelect[0].selectize;
  tagSelectize.clearOptions()
  getBagTagList(function(results){
    tagSelectize.addOption(results.map(function(bagName){
      return {name : bagName}
    }));
  })

}

function hideTaggingOptions(mode, updateValues=false) {
  var modeTag = '#' + mode + 'Tags';

  if(updateValues) {
    var fileNameSelector = '#' + mode + 'BagFileName';
    var categorySelector = '#' + mode + 'BagCategory';
    var tagSelector = '#' + mode + 'BagTags';

    var filename = $(fileNameSelector).val();
    var category = $(categorySelector).val();
    var tags = $(tagSelector).val();

    getBagList(function(results){
      bag_name = results[0].filename
    })

    updateBagMetadata(mode, bag_name, filename, category, tags)
  }
  //TO DO: Wait for the response from the backend before setting the display to none
  document.querySelector(modeTag).style.overflow = "hidden";
  document.querySelector(modeTag).classList.remove('open');
}

function updateBagMetadata(mode, bag_name, modified_bag_name, category, tags) {
  if(!mode) {
    //return //error
  }
  if(!bag_name) {
    //return // error
  }

  var toSend = {
    mode : mode, 
    bag_name : bag_name, 
    modified_bag_name : modified_bag_name, 
    category : category, 
    tags : tags
  }

  triggerService('/aescape/bags/updateBagMeta', toSend)
}

function displayLoadingOptions() {

  selector = "#loadBags";

  document.querySelector(selector).classList.add('open');
  //Putting this in a timeout to wait for the animation to finish completing
  setTimeout(function(){
    document.querySelector(selector).style.overflow = "visible";
  }, 420)

    var $select = $('#loadBagList').selectize({
      valueField: 'filename',
      labelField: 'filename',
      searchField: ['filename', 'category', 'tags'],
      options: [], 
      create: false,
      placeholder : "Select bag to play", 
      render : {
        item: function(item, escape) {
            return '<div class="bag-select-element">' +
              '<div class="bag-select-element">' +
                '<span class="filename">' + escape(item.filename) + '</span>' +
                '<span class="category">' + ' (' + escape(item.category) + ') ' + '</span>' + 
              '</div>' + 
            '</div>';
        },
        option: function(item, escape) {
            var label = item.filename || item.category;
            var caption = item.filename ? item.category : null;
            return '<div class="bag-select-element bag-option">' +
              '<div class="primary">' + 
                '<div class="filename">' + escape(item.filename) + '</div>' +
                '<div class="category">' + escape(item.category) + '</div>' + 
              '</div>' + 
              '<div class="secondary">' + 
                '<div class="tags">' + 
                  item.tags.map(function(tag) {
                    return '<span class="tag label label-info">' + escape(tag) + '</span>' 
                  }).join(' ') + 
                '</div>' +
                '<div class="timestamp">' + escape('27 Jun 10:10am')  + '</div>' + 
              '</div>' + 
            '</div>';
        }
      }
    });  
  
    getBagList(function(results){
      var selectize = $select[0].selectize;
      selectize.clearOptions();
      //results = [{filename : 'testfile', category: 'testcategory', tags : ['testtag1', 'testtag2', 'testtag3']}, {filename : 'testfile2', category: 'testcategory2', tags : ['testtag21', 'testtag22', 'testtag23']}]
      selectize.addOption(results);
      if(results[0]) {
        selectize.setValue(results[0].filename);
      }
    }) 
}

function hideLoadingOptions() {
  var selector = '#loadBags';

  document.querySelector(selector).style.overflow = "hidden";
  document.querySelector(selector).classList.remove('open');
}

