'use strict';
// This is the backend client js
var iosocket = io.connect();

var tbdLable = 'To be determined',
noTeam = 'Kein Team';

// setup all my handlers
iosocket.on('adminrefresh', function(){
  location.reload();
});

iosocket.on('stateChange', function(state){
  $('#team-container').bracket({
    init: state,
    save: saveFn,
    /* without save() labels are disabled */
    decorator: {
      edit: edit_fn,
      render: render_fn
    },
    teamWidth: 130,
    scoreWidth: 20,
    matchMargin: 35,
    roundMargin: 40
  });

  $('.increment').click(function() {
    //alert('haha');
    // trigger a state update?
    //TODO: Focus unfocus on first
  });
  $('.decrement').click(function() {
    //alert('haha');
  });

});


// Bracket editing


/* Custom data objects passed as teams */
var customData = {
  teams: [
    ["Team 1", "Team 2"],
    ["Team 3", "Team 4"]
  ],
  results: []
}

/* Edit function is called when team label is clicked */
function edit_fn(container, data, doneCb) {
  var input = $('<input type="text" style="color:black;">')
  container.html(input)
  input.focus()
  input.blur(function() {
    var inputValue = input.val()
    if (inputValue.length === 0) {
      doneCb(null); // Drop the team and replace with BYE
    } else {
      doneCb(inputValue);
    }
  });
}

/* Render function is called for each team label when data is changed, data
 * contains the data object given in init and belonging to this slot.
 *
 * 'state' is one of the following strings:
 * - empty-bye: No data or score and there won't team advancing to this place
 * - empty-tbd: No data or score yet. A team will advance here later
 * - entry-no-score: Data available, but no score given yet
 * - entry-default-win: Data available, score will never be given as opponent is BYE
 * - entry-complete: Data and score available
 */
function render_fn(container, data, score, state) {
  switch (state) {
    case "empty-bye":
      container.append(noTeam)
      return;
    case "empty-tbd":
      container.append("To be determined")
      return;
    case "entry-no-score":
      console.log('no score');// no return
    case "entry-default-win":
      console.log('default win');// no return
    case "entry-complete":
      container.append(data);
      return;
  }
  console.log(container);
}

function saveFn(data, userData) {
  iosocket.emit('editState', data);
}


$(function() {
  // Dom is loaded
  $('#refresh').click(function() {
    iosocket.emit('clientrefresh');
  });
  // Reading config (not state) from dom... and after all jquery is a doomed dom lib
  tbdLable = $('#TBD').val();
  noTeam = $('#NoT').val();

  // get my state
  var context = 'admin';
  iosocket.emit('loadState', context);
});
