var favorites = [];
var currentSong = null;

// Load jQuery
$(document).ready(function() {
  db = new SongDatabase();
  // db = new SongJar();
  // Populate the song list with them
  onFavoritesChanged();
});

function onFavoritesChanged() {
  // Clear the favorites entirely
  $('#favorites').empty();
  // Then populate them
  db.getSongList(function(songs) {
    $.each(songs, function(index, id) {
      db.getSong(id, function(json) {
        var song = JSON.parse(unescape(json));
        var label = song.artist + ' - ' + song.title;
        $('#favorites').append('<li><a href="#song" onclick="' + getSongLoadJavascript(song) + '">' 
                                + label + '</a></li>');
      });
    });
  });
}

function onSearch() {
  // alert('song searched');
  iui.showPage(document.getElementById('searchResults'));
  // Visually indicate that a song is being searched for
  $('#searchResults').empty().append('<li>Loading...</li>');
  // Form the request path, first getting the query
  var query = $('#query').attr('value');
  var requestURL = '/song/search/?query=' + query;
  // var requestURL = 'searchResults.json';
  // Run an XHR against GU servers
  $.getJSON(requestURL, function(data) {
    // Process the resulting JSON
    $('#searchResults').empty();
    // Create li elements from it and populate the search results dialog
    var songs = '';
    $.each(data.songs, function(index, song) {
      songs += '<li><a href="#song" onclick="' + getSongLoadJavascript(song) + '">' + song.artist + ' - ' + song.title + '</a></li>';
    });
    $('#searchResults').append(songs);
  });
}
function onSearchKeyDown(e) {
  if (event.keyCode == 13) {
    e.preventDefault();
    onSearch();
  }
}
function onFavorite() {
  // alert('adding to favorites');
  db.addSong(currentSong.id, JSON.stringify(currentSong), function() {
    currentSong = null;
    onFavoritesChanged();
  });
}
function onUnFavorite() {
  // alert('removing from favorites');
  db.removeSong(currentSong.id, function() {
    currentSong = null;
    onFavoritesChanged();
  });
}
function onToggleFavorite() {
  db.getSong(currentSong.id, function(json) {
    if (json) {
      onUnFavorite();
    } else {
      onFavorite();
    }
  });
}
function onSongLoad(id, owner) {
  $('#lyrics').text('Please wait: loading song #' + id);
  
  // First try to get the cached version
  db.getSong(id, function(json) {
    var cachedSong = json ? JSON.parse(json) : null;
    
    if (cachedSong) {
      currentSong = cachedSong;
      $('#lyrics').text(getSongText(currentSong));
    } else {
      // Download all of the song data
      var requestURL = '/song/get/' + id + (owner ? '/' + owner : '');
      // var requestURL = 'getSong.json';
      $.getJSON(requestURL, function(data) {;
        currentSong = data.song;
        // Get the text of the song's chords and lyrics
        $('#lyrics').text(getSongText(currentSong));
      });
    }
  });
}
function getSongLoadJavascript(song) {
  if (song.owner) {
    return 'javascript:onSongLoad(' + song.id + ', \'' + song.owner + '\')';
  } else {
    return 'javascript:onSongLoad(' + song.id + ')';
  }
}
function getSongText(song) {

  // text of song with both chords and lyrics
  var songText = '';

  // array of chords in the line. column of the chord is the index in this
  // array
  var lineChords;

  // array of chords - array of lineChords
  var songChords = [];
  
  // preprocess chords forming chord matrix as an array of lineChords
  var chords = song.chords ? JSON.parse(song.chords) : [];
  for (var i = 0, chord; chord = chords[i]; i++) {
    var position = chord.position;

    // create a new chord line array or use already existing
    if(!songChords[position.lineIndex]) {
      // new chord line
      lineChords = [];
      songChords[position.lineIndex] = lineChords;
    }
    else {
      lineChords = songChords[position.lineIndex];
    }

    // assign chord to position
    lineChords[position.charIndex] = chord.name;
  }

  // prepare a plain text view of the song

  // split lyrics into lines
  var lines = song.lyrics.split('\n');
  for (i = 0; i < lines.length; i++) {

    // If it's the first line and there's no text in it, skip it
    if (i == 0 && !lines[i].length) {
      songChords.unshift(null);
      continue;
    }

    // if there is a chord line for this lyrics line
    if(songChords[i]) {
      // form text for the chord line
      var chordLine = formChordLine(songChords[i]);

      // add chord line to song
      songText += chordLine;
      songText += '\n';

    }

    // add lyrics line
    songText += lines[i];
    songText += '\n';
  }

  return songText;
}
// helper function for getSongText
// forms chord line for the array of chords
function formChordLine(chords) {
  var line = '';
  var chordName;

  // for every chord in the line
  for (var i = 0; i < chords.length; i++) {

    // if there is a chord in this position
    if((chordName = chords[i])) {
      // calculate beginning of chord position
      var sIndex = i - parseInt(chordName.length/2);

      // we are assuming that chords can not overlap
      // this will be achieved automatically as new chord is always added
      // to the end
      // fixme: probably need to be more intelligent here
      if(sIndex  > line.length) {
        // fill in with blanks
        var diff = sIndex - line.length;
        for(var j = 0; j < diff; j++) {
          line += ' ';
        }
      }

      // add chord name
      line += chordName;
    }
  }

  return line;
}

