$(document).ready(function(){
    $('.duration').on('change mousemove input', function(){
        $(this).next().html($(this).val() + ' minutes');
    });

    $('.square').height(function(){
        return $(this).width();
    });
    $('.square').css('line-height', function(){
        return $(this).width() + 'px';
    });

    var ws_scheme = 'ws';
    if (window.location.protocol == 'https:'){
      ws_scheme = 'wss';
    }

    function start_ws(){
        var ws = new WebSocket(ws_scheme + "://" + window.location.host + "/websocket");
  
        ws.onmessage = function(evt) {
          var data = JSON.parse(evt.data);
          if(data.operation == 'REFRESH'){
            location.reload();
          }
          if(data.operation == 'VOLUME'){
            $('input.vertical').val(data.volume);
          }
          if(data.operation == 'TRACK_CHANGE'){
            if(data.artist){
                $('.artist').html(data.artist);
            } else {
                $('.artist').html("<i>Artiste inconnu</i>");
            }
            if(data.title){
                $('.title').html(data.title);
            } else {
                $('.title').html('<i>Titre inconnu</i>');
            }
            if(data.picture_mime && data.picture_data){
                $('.picture').html('<img src="data:' + data.picture_mime + ';base64,' + data.picture_data + '" alt="Album cover" />');
            } else {
                $('.picture').html('');
            }
          }
        };
        ws.onclose = function(evt){
            window.setTimeout(start_ws, 100);
        }
        return ws;
    }
    var ws = start_ws();

    $('input.vertical').on('change mousemove input', function(){
        var value = $(this).val();
        if (ws && ws.readyState == 1){
            ws.send(JSON.stringify({
              name: $(this).attr('name'),
              value: value
            }));
        }
        $('input.vertical').val(value);
    });
});
