(function ($, Drupal, drupalSettings) {

  var settings = drupalSettings.edlp_studio;

  function init(){
    console.log('Studio Init');
    initEvents();
    initAjaxLinks();
  };

  function initEvents(){
    $('body')
      .on('new-audio-cartel-loaded', initAjaxChutierLinks)
      .on('new-content-ajax-loaded', initAjaxLinks);
  };

  function initAjaxLinks(){
    initAjaxChutierLinks();
    initAjaxCompoLinks();
  }
  //   ___ _        _   _           _  _         _       _    _      _
  //  / __| |_ _  _| |_(_)___ _ _  | \| |___  __| |___  | |  (_)_ _ | |__ ___
  // | (__| ' \ || |  _| / -_) '_| | .` / _ \/ _` / -_) | |__| | ' \| / /(_-<
  //  \___|_||_\_,_|\__|_\___|_|   |_|\_\___/\__,_\___| |____|_|_||_|_\_\/__/

  function initAjaxChutierLinks(){
    console.log('studio initAjaxChutierLinks');
    $('.chutier-ajax-link:not(.ajax-enabled)')
      .addClass('ajax-enabled')
      .on('click', onClickChutierAjaxLink);
  };

  function onClickChutierAjaxLink(e){
    console.log('studio onClickAjaxLink chutier');
    e.preventDefault();
    addRemoveToChutier($(this));
    return false;
  };

  function addRemoveToChutier($link){
    // var ajax_path = 'edlp_studio/ajax/chutier/add/'+id; // + '/' +cid;
    var ajax_path = $link.attr('data-drupal-link-system-path');
    var path = window.location.origin + drupalSettings.path.baseUrl + ajax_path;
    $link.addClass('ajax-loading');
    $.getJSON(path, {})
      .done(function(data){
        onActionToChutierDone($link, data);
      })
      .fail(function(jqxhr, textStatus, error){
        onErrorActionToChutier(jqxhr, textStatus, error, $link);
      });
  };

  function onActionToChutierDone($link, data){
    console.log('onActionToChutierDone',data);
    $('body').trigger({
      'type':'chutier-action-done',
      'action_done':data.action_done,
      'new_action':data.action_done == 'add' ? 'remove' : 'add',
      'target_id':$link.attr('target_id'),
    });
    $link.replaceWith(data.new_link);
    initAjaxChutierLinks();
    // reload Studio chutier_ui's documents list
    updateStudioChutier();
  };

  function onErrorActionToChutier(jqxhr, textStatus, error, $link){
    console.warn('action to chuttier load failed : '+error, jqxhr.responseText);
  };

  //   ___                        _ _   _
  //  / __|___ _ __  _ __  ___ __(_) |_(_)___ _ _  ___
  // | (__/ _ \ '  \| '_ \/ _ (_-< |  _| / _ \ ' \(_-<
  //  \___\___/_|_|_| .__/\___/__/_|\__|_\___/_||_/__/
  //                |_|
  function initAjaxCompoLinks(){
    console.log('studio initAjaxCompoLinks');
    $('.new-composition-link:not(.ajax-enabled)')
      .addClass('ajax-enabled')
      .on('click', onClickCompoLink);
  };

  function onClickCompoLink(e){
    e.preventDefault();
    setInputForNewCompoName($(this));
    return false;
  };

  function setInputForNewCompoName($link){
    var $form = $('<form>').addClass('new-compo-form')
      .append($('<input>').attr('type', 'text').attr('placeholder', 'new name'))
      .append($('<button>').attr('type', 'submit').html('+'))
      .submit(function(e){
        onNewCompoFormSubmit(e, $link, $(this));
      });

    $link
      .after($form)
      .addClass('folded');
    $form.children('input[type="text"]').focus();
  };

  function onNewCompoFormSubmit(e, $link, $form){
    var name = $('input[type="text"]',$form).val();
    console.log('onNewCompoFormSubmit', name);
    if(name != ''){
      $form.addClass('ajax-loading').children('*').attr('disabled', 'disabled');
      createNewCompo(name, $link, $form);
    }
    e.preventDefault();
  };

  function createNewCompo(name,$link, $form){
    var ajax_path = $link.attr('data-drupal-link-system-path');
    var path = window.location.origin + drupalSettings.path.baseUrl + ajax_path;
    // $link.addClass('ajax-loading');
    $.getJSON(path, {
        'new_name':name
      })
      .done(function(data){
        onActionToCompoDone(data, $link, $form);
      })
      .fail(function(jqxhr, textStatus, error){
        onErrorActionToCompo(jqxhr, textStatus, error, $link);
      });
  };

  function onActionToCompoDone(data, $link, $form){
    console.log('onActionToCompoDone',data);
    $link
      .removeClass('folded')
      .parents('li')
        .before($('<li>').append(data.new_link));
    $form.remove();
    // TODO: open new composition to composer
  };

  function onErrorActionToCompo(jqxhr, textStatus, error, $link){
    console.warn('action to compo load failed : '+error, jqxhr.responseText);
  };


  //  ___ _           _ _              _
  // / __| |_ _  _ __| (_)___ ___ _  _(_)
  // \__ \  _| || / _` | / _ \___| || | |
  // |___/\__|\_,_\__,_|_\___/    \_,_|_|
  // this seems dirty
  function updateStudioChutier(){
    $studioChutier = $('#studio-ui .chutier_ui');
    if($studioChutier.length){
      var ajax_path = settings.chutier_ui_ajax;
      var path = window.location.origin + drupalSettings.path.baseUrl + ajax_path;
      $studioChutier.addClass('loading');
      $.getJSON(path, {})
        .done(function(data){
          onLoadedChutier($studioChutier, data);
        })
        .fail(function(jqxhr, textStatus, error){
          onLoadChutierError(jqxhr, textStatus, error, $studioChutier);
        });
    }
  };

  function onLoadedChutier($studioChutier, data){
    $studioChutier.replaceWith(data.rendered);
    initAjaxChutierLinks();
    $('body').trigger({
      'type':'on-studio-chutier-updated'
    });
  }

  function onLoadChutierError(jqxhr, textStatus, error, $studioChutier){
    console.warn('Chutier load failed', jqxhr.responseText);
    $studioChutier.removeClass('loading');

  }

  init();
})(jQuery, Drupal, drupalSettings);
