
var bagList = Array();

function getBagList(callback)
{
  var service = new ROSLIB.Service({
    ros : ros,
    name : '/aescape/bags/getBagList',
    serviceType : 'demobot/TriggerList'
  });
  
  toSend = {
    message : String(Math.random())
  }

  var request = new ROSLIB.ServiceRequest(toSend);
  
  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) {

  hideAllSlidingControllers();

  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(element){
      return {name : element.filename}
    }));
    if(results[0]) {
      fileNameSelectize.setValue(results[0].filename);
    }
  })
  

  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(element){
      return {name : element}
    }));
  })

  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(element){
      return {name : element}
    }));
  })

}

function hideTaggingOptions(mode, updateValues=false) {
  if(!mode) {
    return;
  }

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



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

    getBagList(function(results){
      if(!(results && results[0] && results[0].filename)) {
        console.log(results);
        displayMessage(false, "Could not retrieve the last recorded bag :(");
        return;
      }
      bag_name = results[0].filename;
      updateBagMetadata(mode, bag_name, filename, category, tags, function(updateError) {
        if(updateError) {
          displayMessage(flase, updateError);
        } else {
          displayMessage("Bag data saved successfully!");
          //clear selectize
            $(fileNameSelector).selectize()[0].selectize.destroy();
            $(categorySelector).selectize()[0].selectize.destroy();
            $(tagSelector).selectize()[0].selectize.destroy();
        }
      });
    })
  }
  //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, callback) {
  if(!mode) {
    return callback();
  }
  if(!bag_name) {
    return callback();
  }

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

  triggerService('/aescape/bags/updateBagMeta', toSend, function(error, result) {
    if(!result) {
      return callback("Something went wrong in the backend while updating.");
    }
    else {
      return callback();
    }
  })
}

function displayLoadingOptions() {

  hideAllSlidingControllers();

  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) {
          filename = item.filename;
          category = item.category || 'None';
            return '<div class="bag-select-element">' +
              '<div class="bag-select-element">' +
                '<span class="filename">' + escape(filename) + '</span>' +
                '<span class="category">' + ' (' + escape(category)  + ') ' + '</span>' + 
              '</div>' + 
            '</div>';
        },
        option: function(item, escape) {
            filename = item.filename;
            category = item.category || 'None';
            return '<div class="bag-select-element bag-option">' +
              '<div class="primary">' + 
                '<div class="filename">' + escape(filename) + '</div>' +
                '<div class="category">' + escape(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>';
        }
      }
    });
    $('#loadBagList').next().find('div.selectize-input > input').prop('disabled', 'disabled');
  
    getBagList(function(results){
      if(!results) {
        displayMessage(false, "Could not fetch a list of recordings :(")
      }
      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);
      }
    })
    
    var $armModeSelect = $('#armMode').selectize({
      valueField: 'value',
      labelField: 'name', 
      options: [], 
      create: false,
      placeholder : "Select dual or single arm mode"
    });  
  
    var armSelectize = $armModeSelect[0].selectize;
    armSelectize.clearOptions()
    armSelectize.addOption([{name: 'Dual-arm', value: false}, {name: 'Single-arm', value: true}]);
    armSelectize.setValue(false);

    $('#armMode').next().find('div.selectize-input > input').prop('disabled', 'disabled');
}

function hideLoadingOptions(loadBag) {
  var singleArmMode = $('#armMode').val();
  if (singleArmMode == "1") {
    singleArmMode = true
  } else {
    singleArmMode = false
  }

  console.log("singleArmMode");
  console.log(singleArmMode)
  if(loadBag) {
    var selectedBagName = $('#loadBagList').val();
    disableUI();
    loadSelectedBagFile(selectedBagName, singleArmMode, function(updateError){
      // if(updateError) {
      //   displayMessage(false, "Something went wrong in the backend while fetching the bag files :(")
      // } else {
      //   displayMessage(true, "Loaded the selected bag file!")
      // }
    })
  } 
  var selector = '#loadBags';
  document.querySelector(selector).style.overflow = "hidden";
  document.querySelector(selector).classList.remove('open');
}




function loadSelectedBagFile(selectedBagName, singleArmMode, callback) {
  var toSend = {
    bag_name : selectedBagName, 
    single_arm : singleArmMode
  }

  // triggerService('/aescape/bags/startPlayingRecording', toSend, function(error, result) {
  //   if(!result) {
  //     return callback("Something went wrong in the backend while updating.");
  //   }
  //   else {
  //     return callback();
  //   }
  // })

  var toSendString = JSON.stringify(toSend);

  var topic = new ROSLIB.Topic({
    ros : ros,
    name : "/left/playback/control",
    messageType : 'std_msgs/String'
  });

  var msg = new ROSLIB.Message({data:toSendString});

  topic.publish(msg);
}


function hideAllSlidingControllers () {
  document.querySelectorAll('.slider-options').forEach(function(element){
    element.style.overflow = "hidden";
    element.classList.remove('open');
  })
}



function displayMessage (success, message) {
  if(success) {
    type = 'success';
  } else {
    type = 'danger';
  }

  $(document).ready(function(){
    $.notify({
      message: message
    }, {
      "placement" : {
        from: "bottom",
        align: "right"
      }, 
      type: type, 
      delay: 1000 
    });
  });
}