{% extends 'base.html' %}

{% block title %}deploy project{% endblock %}

{% block head %}
    <style>
        form {margin: 8px 0;}
        .table {padding-right: 16px;}
        #version{
            background-color: #eee;
            cursor: not-allowed;
            opacity: 1;
        }
        /* https://stackoverflow.com/questions/12441464/aligning-part-of-a-select-options-text-on-the-left-and-part-on-the-right */
        #project_selected, option { font-family: Consolas,  monospace;}
    </style>

    {% if SCRAPYD_SERVERS_AMOUNT > 1 %}
    <script type="text/javascript" src="{{ static_js_multinode }}"></script>
    {% endif %}
{% endblock %}


{% block body %}
<h2>
    <a class="link" target="_blank" href="{{ url }}">
    Add a version to a project, creating the project if it doesn't exist.
    </a>
</h2>


<div class="wrap collapse-wrap">
    <ul class="collapse">
        <li>
            <div class="title">
                <h4>INFO</h4>
                <i class="iconfont icon-right"></i>
            </div>

            <ul>
                <p>Deploying your project involves eggifying it and uploading the egg to Scrapyd.
                    (See <a class="link" target="_blank" href="https://scrapyd.readthedocs.org/en/latest/api.html#addversion-json">Scrapyd addversion.json</a>)
                    You can do this manually, but the easiest way is to use the scrapyd-deploy tool.
                    (See <a class="link" target="_blank" href="https://github.com/scrapy/scrapyd-client">scrapyd-client</a>)
                </p>
                <br>
                <p>Note: Scrapyd uses the distutils LooseVersion to interpret the version numbers you provide.
                    (See <a class="link" target="_blank" href="http://epydoc.sourceforge.net/stdlib/distutils.version.LooseVersion-class.html">_ClassType LooseVersion</a>)
                    And setting the version arbitrarily may cause the scrapyd API 'listversions' to raise error like "builtins.TypeError: '&lt;' not supported between instances of 'str' and 'int'".
                </p>
                <br>
                <p><strong>Auto eggifying (projects in the host where ScrapydWeb runs)</strong></p>
                <li>Step 0: execute the "pip install setuptools" command</li>
                <li>Step 1: set up the 'SCRAPY_PROJECTS_DIR' item for locating projects before starting up ScrapydWeb</li>
                <li>Step 2: select any project found in SCRAPY_PROJECTS_DIR to deploy via this page</li>
                <br>
                <p><strong>Upload egg file</strong></p>
                <li>Step 0: execute the "pip install scrapyd-client" command</li>
                <li>Step 1: cd into your project's root, then execute the "scrapyd-deploy --build-egg projectname.egg" command</li>
                <li>Step 2: upload the built egg via this page</li>
                <br>
                <p><strong>Upload compressed file</strong></p>
                <li>Step 1: compress your project folder into an archive file (.zip) with an archiving software or via the tar command:
                    <pre>tar -czvf projectname.tar.gz /path/to/your/projectname</pre>
                </li>
                <li>Step 2: upload the compressed file via this page</li>
            </ul>
            <br>
        </li>
    </ul>
</div>


{% if SCRAPYD_SERVERS_AMOUNT > 1 %}
<div class="wrap">
    <h3><a href="{{ url_overview }}">Simply pass in a group of nodes from the Overview page &raquo;</a></h3>
    <form method="post" action="{{ url_deploy_upload }}" enctype="multipart/form-data">
        <input type="text" name="checked_amount" value="1" hidden />
        <div class="multiselect">
            <div class="selectBox" onclick="showCheckboxes()">
                <select>
                    <option id="selected_nodes_statement">{{ SCRAPYD_SERVERS[node-1] }}</option>
                </select>
                <div class="overSelect"></div>
            </div>
            <div id="checkboxes">
                <label for="checkcurrent">
                    <input type="checkbox" id="checkcurrent" />Check current node only
                </label>
                <label for="checkall">
                    <input type="checkbox" id="checkall" />CheckAll / UncheckAll
                </label>
                <div id="nodes_checkboxes">
                {% for SCRAPYD_SERVER in SCRAPYD_SERVERS %}
                    {% if SCRAPYD_SERVERS_GROUPS[loop.index-1] and loop.changed(SCRAPYD_SERVERS_GROUPS[loop.index-1]) %}
                    <span> --- {{ SCRAPYD_SERVERS_GROUPS[loop.index-1] }} --- </span>
                    {% endif %}

                    <label id="label_{{ loop.index }}" for="checkbox_{{ loop.index }}">
                        <input type="checkbox" id="checkbox_{{ loop.index }}" name="{{ loop.index }}"
                        {% if loop.index in selected_nodes %}
                        checked
                        {% endif %}
                        />
                        {{ SCRAPYD_SERVER }}
                    </label>
                {% endfor %}
                </div>
            </div>
        </div>
    </form>
</div>
{% else %}
<form method="post" action="{{ url_deploy_upload }}" enctype="multipart/form-data">
</form>
{% endif %}


<div class="tab-wrap wrap">
    <ul class="tab tab-header clear-float">
        <li {% if SCRAPY_PROJECTS_DIR != "" %}class="active"{% endif %}>Auto eggifying</li>
        <li {% if SCRAPY_PROJECTS_DIR == "" %}class="active"{% endif %}>Upload egg or compressed file</li>
    </ul>
    <ul class="tab tab-content">
        <li {% if SCRAPY_PROJECTS_DIR != "" %}class="active"{% endif %}>
            <div class="upload">
                <div>
                    {% if SCRAPY_PROJECTS_DIR == "" %}
                    <h3>Set up the 'SCRAPY_PROJECTS_DIR' item for locating projects before starting up ScrapydWeb</h3>
                    {% else %}
                    <h3>{{ projects|length|string + " projects found in '" + SCRAPY_PROJECTS_DIR + "' of the host where ScrapydWeb runs" }}</h3>
                    {% endif %}

                    <select id="project_selected" name="project"
                    style="height: 30px; width: 440px; font-size: 18px;"
                    onchange="console.log(my$('#project_selected').value);">
                    {% for project in projects %}
                        <option value ="{{ project }}" style="font-size: 18px;">
                        {{ ' %-20s %s '|format(project, modification_times[loop.index0])|replace(" ", "&nbsp;")|safe }}
                        </option>
                    {% endfor %}
                    </select>

                    <a class="button safe" href="javascript:;" onclick="eggify();">
                    Eggify & Deploy
                    </a>
                </div>
            </div>
        </li>

        <li {% if SCRAPY_PROJECTS_DIR == "" %}class="active"{% endif %}>
            <h3>Check out the INFO section above to get help</h3>
            <div class="upload">
                <label class="upload-button">
                    <!-- macOS cannot select '.tar.gz' file if '.tar.gz' is added in accept -->
                    <input id="file" type="file" name="file" accept=".egg, .zip, .gz" />
                    Select
                </label>
                <span class="filename">an egg/zip/tar.gz file containing the project's code</span>

                <div class="table vertical-table">
                    <table>
                        <tr>
                            <th>project</th>
                            <td><input id="project" name="project" placeholder="the project name" /></td>
                        </tr>
                        <tr>
                            <th>version</th>
                            <td><input readonly="readonly" id="version" name="version" placeholder="the project version" /></td>
                        </tr>
                    </table>
                </div>

                <a href="javascript:;" class="submit" onclick="uploadEggfile();">
                    <i class="iconfont icon-upload"></i>
                </a>
            </div>
        </li>
    </ul>
</div>


<script>
//Avoid var projects = [u'12345678901234567890',]
var projects = [{% for project in projects %}'{{ project }}', {% endfor %}];
var modification_times = {{ modification_times|safe }};

function eggify(){
    {% if projects|length == 0 %}
        {% if SCRAPY_PROJECTS_DIR == "" %}
            alert("Set up the 'SCRAPY_PROJECTS_DIR' item to locate your projects and eggify them automatically");
            return;
        {% else %}
            alert("NO projects found in '{{ SCRAPY_PROJECTS_DIR }}' of the host where ScrapydWeb runs");
            return;
        {% endif %}
    {% endif %}

    {% if SCRAPYD_SERVERS_AMOUNT > 1 %}
    if (checked_amount == 0) {
        alert("Select at least one node");
        return;
    }
    {% endif %}

    var project = my$('#project_selected').value;
    var version = modification_times[projects.indexOf(project)];
    console.log(project);
    console.log(version);

    var form = my$('form');

    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'project';
    input.value = project;
    form.appendChild(input);

    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'version';
    input.value = version;
    form.appendChild(input);

    my$('form').submit();
    showLoader();
}
</script>


<script>
// Put off
{% if SCRAPYD_SERVERS_AMOUNT > 1 %}
window.onload = function() {
    {% if selected_nodes == [] %}
    if (window.localStorage && JSON.parse(localStorage.getItem('nodesSelected') || "[]").length != 0) {
        var nodesSelected = JSON.parse(localStorage.getItem('nodesSelected') || "[]");
        var nodesSelected_new = [];
        for (idx in nodesSelected) {
            try {
                var n = nodesSelected[idx];
                my$('#checkbox_'+n).checked = true;
                nodesSelected_new.push(n);
            } catch(err) {console.log(err);}
        }
    } else {
        my$('#checkbox_'+{{ node }}).checked = true;
    }
    {% endif %}

    $('#checkall').click(function () {
        $('#checkboxes input:checkbox').not(this).prop('checked', this.checked);
        my$('#checkcurrent').checked = false;
    });

    $('#checkcurrent').click(function () {
        $('#checkboxes input:checkbox').not(this).prop('checked', false);
        my$('#checkcurrent').checked = true;
        my$('#checkbox_'+{{ node }}).checked = true;
    });

    $('#checkboxes input[type=checkbox]').change(function() {
        checkCheckboxes({{ SCRAPYD_SERVERS_AMOUNT }});
    });

    checkCheckboxes({{ SCRAPYD_SERVERS_AMOUNT }}); //For navigate back
}
{% endif %}

my$("#file").onchange = function() {
    my$('.filename').innerText = "an egg/zip/tar.gz file containing the project's code";

    var eggfile = my$('#file').files[0];
    if(eggfile === undefined) {
        //my$('form').reset();
        my$('#project').value = '';
        my$('#version').value = '';
        return;
    }

    var parts = eggfile.name.split('.');
    var filetype = parts[parts.length - 1];
    if(['egg', 'zip'].indexOf(filetype) == -1 && eggfile.name.indexOf('.tar.gz') == -1) {
        //my$('form').reset();
        my$('#project').value = '';
        my$('#version').value = '';
        alert("Select an egg/zip/tar.gz file containing the project's code");
        return;
    }

    my$('.filename').innerText = eggfile.name;
    my$('#project').value = parts[0];
    //my$('#version').value = eggfile.lastModifiedDate.toISOString().slice(0,19).replace(/:/g, "_");
    var d = new Date(eggfile.lastModified);
    d.setMinutes(d.getMinutes()-d.getTimezoneOffset());
    my$('#version').value = d.toISOString().slice(0,19).replace(/:/g, "_");
    console.log(my$('#version').value);
};


function uploadEggfile() {
    var project = my$('#project').value;
    var version = my$('#version').value;

    if(my$('#file').files[0] === undefined) {
        alert("Select an egg/zip/tar.gz file containing the project's code");
        return;
    } else if(project == '') {
        alert("the project name is required");
        return;
    } else if(version == '') {
        alert("the project version is required");
        return;
    }

    {% if SCRAPYD_SERVERS_AMOUNT > 1 %}
    if (checked_amount == 0) {
        alert("Select at least one node");
        return;
    }
    {% endif %}

    var form = my$('form');

    var input = my$('#file').cloneNode(true);
    input.style = "display: none;";
    form.appendChild(input);

    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'project';
    input.value = project;
    form.appendChild(input);

    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'version';
    input.value = version;
    form.appendChild(input);

    my$('form').submit();
    showLoader();
}
</script>

<script>
// handle collapse components
(function () {
    var collapse = my$('.collapse');
    var titles = my$$('.collapse .title');
    var lis = my$$('.collapse li');
    titles.forEach(function(title) {
        title.addEventListener('click', function(e){
            var index = [].indexOf.call(titles, this);
            lis[index].classList.toggle('active');
        });
    });
})();
</script>

<script>
// tab switcher
(function() {
    var index = -1;
    var tabHeaders = my$$('.tab-header>li');
    var tabContents = my$$('.tab-content>li');
    my$('.tab-header').addEventListener('click', function(e) {
        var target = e.target;
        //console.log(target.id);
        if (target.tagName.toLowerCase() !== 'li') return;
        index = Array.prototype.indexOf.call(tabHeaders, target);
        tabHeaders.forEach(function(el) {
            el.classList.remove('active');
        });
        target.classList.add('active');
        tabContents.forEach(function(el) {
            el.classList.remove('active');
        });
        tabContents[index].classList.add('active');
    });
})();
</script>
{% endblock %}
