{% extends "wooey/base.html" %}
{% load i18n %}
{% load wooey_tags %}

{% block breadcrumbs %}
    <li><a href="#">{{ script.script_name }}</a></li>
{% endblock %}

{% block left_sidebar %}{% endblock left_sidebar %}
{% block center_content_class %}col-md-12 col-xs-12{% endblock center_content_class %}

{% block center_content %}

    <div class="page-header">
        <h3 id="wooey-script-title">{{ script.script_name }}</h3>
        <p id="wooey-script-description">{{ script.script_description }}</p>
    </div>

  <div class="container-fluid">

        {% if script.documentation %}
        <div class="panel panel-default">
            <div class="panel-heading">{% trans "Documentation" %} <a class="icon icon-collapse" data-toggle="collapse" data-target="#collapse-metadata" href="#collapse-metadata"></a></div>
            <div id="collapse-metadata" class="panel-collapse collapse in">
            <div class="panel-body markdown">{{ script.documentation }}</div>
            </div>
        </div>
        {% endif %}


    <form id="wooey-job-form" method="POST" action="{{ form.action }}" enctype="multipart/form-data">
        {% csrf_token %}

        <div class="panel panel-default">
        <div class="panel-heading">
            {% trans "Settings" %}
            <a class="icon icon-collapse" data-toggle="collapse" data-target="#collapse-settings" href="#collapse-settings"></a>
        </div>

        <div id="collapse-settings" class="panel-collapse collapse in">

        <div class="panel-nav-tabs">
        <ul class="nav nav-tabs">
        {% for group in form.groups %}
            {% with group.group_name|slugify as group_slug %}
            <li class="{% if forloop.first %}active{% endif %}"><a data-toggle="tab" href="#optiongroup-{{ group_slug }}">{{ group.group_name|title }}</a></li>
            {% endwith %}
        {% endfor %}
        </ul>
        </div>

        <div class="panel-body">
        <div class="tab-content">
        {% for group in form.groups %}
        {% with group.group_name|slugify as group_slug %}

          <div id="optiongroup-{{ group_slug }}" class="tab-pane fade in {% if forloop.first %}active{% endif %}">

            {% for field in group.form %}
                <div class="form-group row">
                {{ field.errors }}
                {% if not field.is_hidden %}
                <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                {% endif %}
                {{ field }}
                {% if not field.is_hidden %}
                <p class="help-block">{{ field.help_text }}</p>
                {% endif %}
                </div>
            {% endfor %}
          </div>

        {% endwith %}
        {% endfor %}

        </div>
        </div>
        </div>

        </div>


        <div class="panel panel-default">
            <div class="panel-heading">{% trans "Metadata" %} <a class="icon icon-collapse" data-toggle="collapse" data-target="#collapse-metadata" href="#collapse-metadata"></a></div>
            <div id="collapse-metadata" class="panel-collapse collapse in">
            <div class="panel-body">

                <div class="form-group row">
                    <label for="job-name">{% trans "Job Name" %}</label>
                    <input class="form-control" id="wooey_job_name" type="text" id="job-name" name="job_name" placeholder="{% trans "Job Name" %}" value="{{ script.script_name }} {% now "Ymd-G:i" %}"/>
                </div>
                <div class="form-group row">
                    <label for="job-description">{% trans "Job Description" %}</label>
                    <textarea class="form-control" id="wooey_job_description" cols="30" rows="5" id="job-description" name="job_description" placeholder="{% trans "Enter job description here..." %}"></textarea>
                </div>
            </div>
            </div>
            </div>

        <input name="wooey_clone_task_id" id="wooey_clone_task_id" type="hidden">
        <div class="pull-right">
            <button id="wooey-form-submit" type="submit" class="btn btn-primary">{% trans "Submit" %}</button>
        </div>
    </form>
</div>

{% endblock center_content %}

{% block inline_js %}
{{ block.super }}
<script  type="text/javascript">


        $(document).ready(function(){
            var filesUploaded = {};

            var multi_selector = 'a[href=#wooey-multi-input]';
            var wooey_remove_selector = 'a[href=#wooey-multi-input-remove]';
            var all_multi_selectors = 'a[href=#wooey-multi-input], a[href=#wooey-multi-input-remove]';
            var wooey_multiple_selector = '[data-wooey-multiple]';
            var wooey_choice_limit = 'wooey-choice-limit';

            var maxChoices = function($element){
                $element.popover({
                    content: "{% trans "No more choices may be added for this selection" %}",
                    trigger: 'manual'
                }).popover('show');
                setTimeout(function(){$element.popover('destroy')}, 1000);
            };

            var initializeWooeyScript = function(){
                // Add the - button so users can remove elements from cloned jobs
                $(wooey_multiple_selector).parent().each(
                    function(element, value){
                        var $wooey_multiples = $(value).find(wooey_multiple_selector);
                        if($wooey_multiples.length != 1) {
                            for (var i = 0; i < $wooey_multiples.length; i++) {
                                var $remove_button = removeMultiInput();
                                $remove_button.appendTo($wooey_multiples[i]);
                            }
                        }
                    }
                );

                var $multi_selector = $(multi_selector);
                $multi_selector.click(function(event){
                    event.preventDefault();
                    var $this = $(this);

                    var $containers = $this.siblings(wooey_multiple_selector);
                    // check the choice limit, are we at it?
                    var choice_limit = $this.data(wooey_choice_limit);
                    if(choice_limit && ($containers.length == choice_limit)){
                        // give a notice
                        maxChoices($this);
                        return;
                    }

                    var $container = $containers.first();
                    // if the container doesn't have a remove button since it's the first one, add one
                    if($container.find(wooey_remove_selector).length == 0){
                        removeMultiInput().appendTo($container);
                    }
                    var $new_target = $container.clone();
                    $new_target.insertAfter($container);
                    // remove any existing removal buttons from the container
                    $new_target.find(all_multi_selectors).remove();
                    // add a way to remove the new container
                    var $remove_button = removeMultiInput();
                    $remove_button.appendTo($new_target);
                });

                // setup the choice limits for select fields
                $('select[data-wooey-choice-limit] option').click(function(event){
                    var $this = $(this);
                    var $select = $this.parent();
                    var choice_limit = $select.data(wooey_choice_limit);
                    var selected = $select.find(':selected').length;
                    if(choice_limit && (selected > choice_limit)){
                        $this.prop("selected", false);
                        maxChoices($select);
                        return;
                    }
                })
            };


            var removeMultiInput = function(){
                var $remove_input = $('<a href="#wooey-multi-input-remove"><span class="glyphicon glyphicon-minus"></span></a>');
                $remove_input.click(function(event){
                    event.preventDefault();
                    var $multi_input = $(this).parent(wooey_multiple_selector);

                    // all other containers with multi-selections for this parameter
                    var $others = $multi_input.siblings(wooey_multiple_selector);
                    // remove us
                    $multi_input.remove();
                    // if there is only 1 container left, remove the button to remove it
                    if($others.length == 1){
                        $others.find(wooey_remove_selector).remove();
                    }
                });
                return $remove_input;
            };

            var loadWooeyScript = function(url, params, form){
                $.get(url, params, function(data){
                    form.attr('action', data.action);
                    var $wooey_tabs = form.find('#wooey-script-tabs');
                    var $wooey_content = form.find('#wooey-script-content');
                    for(var i=0;i<data.groups.length;i++){
                        $wooey_tabs.append('<li class="wooey-dynamic-tabs" role="presentation"><a href="#wooey_dynamic_tab'+i+'" aria-controls="profile" role="tab" data-toggle="tab">'+data.groups[i].group_name+'</a></li>');
                        var new_panel = $('<div role="tabpanel" class="tab-pane wooey-dynamic-tabs" id="wooey_dynamic_tab'+i+'"></div>');
                        new_panel.html(data.groups[i].form);
                        $wooey_content.append(new_panel);
                    }
                    var $first = $('a[href="#wooey_dynamic_tab0"]');
                    if($first.length)
                        $first.trigger('click');
                    initializeWooeyScript();
                }, "json");
            };

            var updateScriptInfo = function(url){
                // set the details of what script we clicked
                $('.wooey-dynamic-tabs').remove();
                var $scriptBox = $("a[data-href='"+url+"']");
                var title = $scriptBox.find('.wooey-script-title').text();
                var desc = $scriptBox.find('.wooey-script-description').text();
                $('#wooey-script-description').text(desc);
                var $title = $('#wooey-script-title');
                $title.text(title);
                var currentTop = $(document).scrollTop();
                var scriptTop = $title.closest('.center-div').offset().top;
                if (currentTop > scriptTop)
                    window.scrollTo(0, scriptTop);
            };

            {% if job_info %}
                // Track file changes
                $("input:file").change(function (){
                   var fileName = $(this).val();
                   filesUploaded[$(this).attr('name')] = fileName;
                 });
                var $jobform = $('#wooey-job-form');
                updateScriptInfo('{{ job_info.data_url }}');
                loadWooeyScript('{{ job_info.url }}', {job_id: '{{ job_info.job_id }}'}, $jobform);
                $jobform.find('#wooey_clone_job_id').val("{{ job_info.job_id }}");
            {% endif %}
            initializeWooeyScript();

            $('#wooey-form-submit').click(function(event){
                event.preventDefault();
                var $form = $(this).closest('form');
                // if we are cloning a job, we need to specify the fields as the files because the file type input
                // will be blank
                var formData = new FormData($form[0]);
                $('input[type="file"]').each(function(index, value){
                    if(filesUploaded[$(this).attr('name')] === undefined){
                        // the user has not selected a file to replace this one
                        formData.append($(this).attr('name'), $(this).siblings('a').text());
                    }
                });
                $.ajax({
                    url: $form.attr('action'),
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function(data){
                        clearErrors($form);
                        if(data.valid){
                            // clear form and indicate they can proceed
                            $form[0].reset();
                            location.href = data.redirect;
                        }
                        else{
                            processErrors($form, data.errors)
                        }
                    }
                });
            });
        });
</script>
{% endblock inline_js %}
