{% load staticfiles %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Saas dm storage</title>
    <link href="https://yandex.st/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
    <link href="{% static 'css/font-awesome.min.css' %}" rel="stylesheet"/>
</head>
<script type='text/javascript' src="{% static 'js/xmlhttp.js' %}"></script>
<script src="https://yandex.st/jquery/2.0.3/jquery.min.js"></script>
<script src="https://yandex.st/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script type='text/javascript' src="{% static 'js/answer_set.js' %}"></script>

<style>
    .fa-file {
        color: #f1f1c2;
    }
    .fa-file-o {
        color: #f1f1c2;
    }
    .fa-folder {
        color: #f1f1c2;
    }
    .fa-folder-o {
        color: #f1f1c2;
    }
</style>

<script type='text/javascript'>
    let current_path = '{{ storage.path }}';
    let current_is_file = {% if storage.is_file %}true{% else %}false{% endif %};
    let current_version = -1;
    let current_files = [];

    function parse_answer(xmlhttp) {
        if (xmlhttp.status === 200) {
            try {
                let res = JSON.parse(xmlhttp.responseText);
                if (res['success']) {
                    set_answer(statuses.ok, xmlhttp.status + ' ' + xmlhttp.responseText);
                    return true;
                } else {
                    set_answer(statuses.error, xmlhttp.status + ' ' + xmlhttp.responseText);
                    return false;
                }
            } catch (err) {
                console.log(err);
                set_answer(statuses.error, xmlhttp.status + ' ' + xmlhttp.responseText);
                return false;
            }
        } else {
            set_answer(statuses.error, xmlhttp.status + ' ' + xmlhttp.responseText);
            return false;
        }
    }

    function send_file() {
        let fc = document.getElementById("fcontent").value;
        let xmlhttp = getXmlHttp();
        xmlhttp.open('POST', '{%  url "storage_modify" %}?action=set&path=' + current_path, true);
        xmlhttp.send(fc);
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState === 4) {
                parse_answer(xmlhttp);
            }
        };
    }

    function indicate_download(path) {
        set_answer(statuses.attention, 'file ' + path + ' started to download, wait a minute');
    }

    function remove_from_storage(path, is_file) {
        let cfm = confirm('ARE YOU SURE to remove path ' + path + '?');
        if (!cfm) { return; }
        set_answer(statuses.loading, 'removing '+ path + '...');
        let url = '{% url "storage_remove" %}?path=' + path + '&is_file=' + is_file;
        let xmlhttp = getXmlHttp();
        xmlhttp.open('GET', url);
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState === 4) {
                parse_answer(xmlhttp);
            }
        };
        xmlhttp.send();
    }

    function bin2hex(s) {
        let i, f = s.length, a = [];
        for (i = 0; i < f; i++) {
            let c = s.charCodeAt(i).toString(16);
            a[i] = c.length < 2 ? '0' + c : c;
        }
        return a.join('');
    }

    function get_full_path(name) {
        let full_path = '';
        let parent = current_path;
        if (parent[parent.length - 1] === '/') {
            parent = parent.slice(0, -1);
        }
        if (current_is_file) {
            let parts = parent.split('/');
            parts[parts.length - 1] = name;
            full_path = parts.join('/');
        } else {
            full_path = parent + '/' + name;
        }
        return full_path;
    }

    function fill_uploaded_filename() {
        let up_el = document.getElementById('file-to-upload');
        let files = up_el.files;
        if (files.length === 0) {
            document.getElementById('upload-filename').value = "";
            return;
        }
        document.getElementById('upload-filename').value = files[0].name;
    }

    function upload_file() {
        let up_path = document.getElementById('upload-filename').value;
        if (up_path === '') {
            alert('empty filename field, fill it');
            return;
        }
        let is_new_file = (current_files.indexOf(up_path) === -1);
        up_path = get_full_path(up_path);
        let up_el = document.getElementById('file-to-upload');
        let files = up_el.files;
        if (files.length === 0) {
            alert('no file selected to upload');
            return;
        }
        let up_file = files[0];
        let reader = new FileReader();
        set_answer(statuses.loading, 'loading file ' + up_file.name + '...');
        reader.onload = (function(theFile, thePath, rebuildTree) {
            return function(e) {
                console.log('read ' + e.target.result.length + ' bytes, will send as ' + thePath);
                set_answer(statuses.loading, 'uploading path ' + thePath + '...');
                let xmlhttp = getXmlHttp();
                xmlhttp.open('POST', '{%  url "storage_modify" %}?action=set&hex=1&path=' + thePath, true);
                xmlhttp.send(bin2hex(e.target.result));
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState === 4) {
                        let success = parse_answer(xmlhttp);
                        if (success) {
                            try {
                                document.getElementById('upload-filename').value = '';
                                document.getElementById('file-to-upload').value = "";
                            } catch(err) { console.log(err); }
                            if (rebuildTree) {
                                setTimeout(function(){navigate(current_path, -1)}, 2000);
                            }
                        }
                    }
                };
            };
        })(up_file, up_path, is_new_file);
        reader.readAsBinaryString(up_file);
    }

    function create_file() {
        let name = document.getElementById('create-filename').value;
        if (name === '') {
            alert('filename empty, fill it');
            return;
        }
        if (current_files.indexOf(name) !== -1) {
            alert('file ' + name + ' already exists');
            return;
        }
        let cr_path = get_full_path(name);
        let fc = document.getElementById("fcontent").value;
        let xmlhttp = getXmlHttp();
        xmlhttp.open('POST', '{%  url "storage_modify" %}?action=set&path=' + cr_path, true);
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState === 4) {
                let success = parse_answer(xmlhttp);
                if (success) {
                    setTimeout(function() { navigate(cr_path, -1) });
                }
            }
        };
        xmlhttp.send(fc);
    }

    function fetch_fml_file() {
        let fml_id = document.getElementById('fml-formula-id').value;
        let fml_fn = document.getElementById('fml-filename').value;
        if (fml_id === '' || fml_fn === '') {
            alert('formula id or filename not set, fill it');
            return;
        }
        let parent=get_full_path('');
        let filename = fml_fn + '.info-' + detect_service();
        let url = '{% url "storage_fetch_fml" %}?fml_id=' + fml_id + '&file_name=' + filename + '&parent_path=' + parent;
        console.log(url);
        let xmlhttp = getXmlHttp();
        xmlhttp.open('GET', url);
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState === 4) {
                let success = parse_answer(xmlhttp);
                if (success) {
                    setTimeout(function() { navigate(current_path, -1) });
                }
            }
        };
        xmlhttp.send();
    }

    function detect_service() {
        let parts = current_path.split('/');
        let cfind = parts.indexOf('configs');
        if (cfind === -1 || cfind === parts.length - 1) {
            return '';
        }
        return parts[cfind + 1];
    }

    function switch_fml_element() {
        let el = document.getElementById('storage-fml-copy');
        if (el.hasAttribute('hidden')) {
            let service = detect_service();
            document.getElementById('service-for-fml').innerHTML = service;
            el.removeAttribute('hidden');
        } else {
            el.setAttribute('hidden', 1);
        }
    }

    function clear_links(parent_path) {
        let el = document.getElementById('navigation_td');
        el.innerHTML = '';
        gen_link(parent_path, '..', false);
    }

    function set_answer(status, answer) {
        let ans_el = document.getElementById('answer');
        ans_el.innerHTML = answer;
        let color = 'blue';
        if (status === statuses.ok) {
            color = 'lightgreen';
        } else if (status === statuses.error) {
            color = 'red';
        } else if (status === statuses.loading) {
            color = 'beige';
        } else if (status === statuses.attention) {
            color = '#f5c42f';
        }
        ans_el.style.borderLeft = '5px solid ' + color;
    }

    function do_gen_link(full_path, name, is_file, parent_tag, add_icon) {
        let link_el_p = document.createElement(parent_tag);
        let color = is_file ? 'green' : 'brown';
        if (add_icon) {
            let ico_dd_el = document.createElement('span');
            ico_dd_el.className = 'dropdown';
            let ico_el = document.createElement('i');
            let fa_cls = is_file ? 'fa fa-file-o' : 'fa fa-folder-o';
            ico_el.setAttribute('data-toggle', 'dropdown');
            let menu_el = document.createElement('ul');
            menu_el.className = 'dropdown-menu';
            if (is_file) {
                let download_el = document.createElement('li');
                let dlink = '{% url "storage_download" %}';
                download_el.innerHTML = '<a onclick="indicate_download(\'' + full_path + '\')" href="' + dlink + '?path=' + full_path + '" download="' + name + '" target="_blank">download</a>';
                menu_el.appendChild(download_el);

                let upload_el = document.createElement('li');
                upload_el.innerHTML = '<a onclick="upload_prep(\'' + name + '\')" style="cursor:pointer">upload</a>';
                menu_el.appendChild(upload_el);
            }
            if (name.indexOf('..') === -1) {
                let remove_el = document.createElement('li');
                remove_el.innerHTML = '<a onclick="remove_from_storage(\'' + full_path + '\', ' + is_file + ')" style="cursor:pointer">remove</a>';
                menu_el.appendChild(remove_el);
            } else {
            }

            // ico_el.style.color = color;
            ico_el.style.marginRight = '2px';
            ico_el.className = fa_cls + ' dropdown-toggle';
            ico_dd_el.style.float = 'right';
            ico_el.style.marginRight = '5px';

            ico_dd_el.appendChild(ico_el);
            ico_dd_el.appendChild(menu_el);
            link_el_p.appendChild(ico_dd_el);
//            ico_dd_el.hidden = true;
        }
        let link_el = document.createElement('a');
        link_el.innerHTML = name.replace(new RegExp('_', 'g'), '<wbr>_');
        link_el.onclick = function(){ navigate(full_path, -1) };
       // link_el.innerHTML = '<a onclick="navigate(\'' + full_path + '\', -1)">' + name + '</a>';
        link_el.style.color = is_file ? 'green' : 'brown';
        // link_el.style.textDecoration = 'underline';
        link_el.style.cursor = 'pointer';
        link_el_p.appendChild(link_el);
        return link_el_p;
    }

    function gen_link(full_path, name, is_file) {
        let el = document.getElementById('navigation_td');
        let link_el = do_gen_link(full_path, name, is_file, 'div', true);
        if (is_file) {
            link_el.style.borderBottom = '1px solid #cbeacb';
        } else {
            link_el.style.borderBottom = '1px solid #d9c8c8';
        }
        el.appendChild(link_el);
    }

    function fill_dirs(base_path, parent_path, storage_tree) {
        clear_links(parent_path);
        current_files = [];
        try {
            for (let i=0; i<storage_tree['dirs'].length; ++i) {
                gen_link(base_path+ '/' + storage_tree['dirs'][i], storage_tree['dirs'][i], false);
            }
        } catch(err) { console.log(err); }
        try {
            for (let j=0; j<storage_tree['files'].length; ++j) {
                gen_link(base_path + '/' + storage_tree['files'][j], storage_tree['files'][j], true);
                current_files.push(storage_tree['files'][j]);
            }
        } catch(err) { console.log(err); }
    }

    function ensure_element_hidden(id, must_be_hidden) {
        try {
            let el = document.getElementById(id);
            if (must_be_hidden && !el.hasAttribute('hidden')) {
                el.setAttribute('hidden', 1);
            }
            if (!must_be_hidden && el.hasAttribute('hidden')) {
                el.removeAttribute('hidden');
            }
        } catch(err)  {console.log(err); }
    }

    function switch_element_hidden(id) {
        try {
            let el = document.getElementById(id);
            if (el.hasAttribute('hidden')) {
                el.removeAttribute('hidden');
            } else {
                el.setAttribute('hidden', 1);
            }
        } catch(err)  {console.log(err); }
    }

    function upload_prep(name) {
        document.getElementById('upload-filename').value = name;
        ensure_element_hidden('storage-upload', false);
    }

    function update_buttons(is_file) {
        ensure_element_hidden('b_send_file', !is_file);
        ensure_element_hidden('versions', !is_file);
    }

    function gen_head_link() {
        let cp = document.getElementById('current-path');
        cp.innerHTML = '';
        let root_link = do_gen_link('/', 'root', false, 'span', false);
        cp.appendChild(root_link);
        let parts = current_path.split('/');
        let full_path = '';
        for (let i=0; i<parts.length; ++i) {
            if (parts[i] === '') {
                continue;
            }
            full_path += '/' + parts[i];
            let is_file = false;
            if (i === parts.length - 1) {
                is_file = current_is_file;
            }
            let link = do_gen_link(full_path, parts[i], is_file, 'span', false);
            let slash_el = document.createElement('span');
            slash_el.innerHTML = '/';
            cp.appendChild(slash_el);
            cp.appendChild(link);
        }
        let nw_link_el = document.getElementById('storage-new-window-link');
        nw_link_el.href = '{% url "storage" %}?path=' + current_path;
    }

    function build_versions(el, versions) {
        el.innerHTML = 'Versions: ';
        for (let i=versions.length; i>0; --i) {
            let ver_el = document.createElement('a');
            ver_el.innerHTML = versions[i-1];
            ver_el.style.marginLeft = '5px';
            ver_el.style.cursor = 'pointer';
            ver_el.style.color = 'black';
            if (versions[i-1] === current_version) {
                ver_el.style.fontWeight = 'bold';
            }
            ver_el.onclick = navigate.bind(null, current_path, versions[i-1]);
            el.appendChild(ver_el);
        }
    }

    function get_versions(path) {
        let vid = document.getElementById('versions');
        vid.innerHTML = 'Versions loading...';
        let xmlhttp = getXmlHttp();
        xmlhttp.open('GET', '{% url "storage_versions" %}?path=' + path);
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState === 4) {
                try {
                    let vers = JSON.parse(xmlhttp.responseText);
                    if (!vers['success']) {
                        vid.innerHTML = 'Versions error: ' + xmlhttp.responseText;
                    } else {
                        build_versions(vid, vers['versions']);
                    }
                } catch(err) {
                    vid.innerHTML = 'Versions error: ' + xmlhttp.responseText;
                }
            }
        };
        xmlhttp.send();
    }

    function ClearFormatInfo() {
        let format_el = document.getElementById('format_detect');
        format_el.innerHTML = '';
        if (format_el.hasAttribute('isjson')) {
            format_el.removeAttribute('isjson');
        }
    }
    function JsonCheck() {
        let format_el = document.getElementById('format_detect');
        let wasJson = format_el.hasAttribute('isjson');
        try {
            let val = document.getElementById('fcontent').value;
            if (val.length > 500000) { return; }
            JSON.parse(val);
            format_el.innerHTML = 'This is pure JSON';
            format_el.setAttribute('isjson', 1);
            format_el.style.color = '#5dad5d';
        } catch (err) {
            if (wasJson) {
                format_el.innerHTML = 'This is not pure JSON now';
                if (format_el.hasAttribute('isjson')) {
                    format_el.removeAttribute('isjson');
                }
                format_el.style.color = '#c1717c';
            }
        }
    }

    function navigate(new_path, new_version) {
        document.getElementById('fcontent').value = '';
        ClearFormatInfo();
        ensure_element_hidden('storage-fml-copy', true);
        set_answer(statuses.loading, 'Loading ' + new_path + '...');
        if (current_path !== new_path) {
            document.getElementById('versions').innerHTML = '';
        }
//        current_path = new_path;

        let xmlhttp = getXmlHttp();
        let url = '{% url "storage" %}?format=json&path=' + new_path;
        if (new_version !== -1) {
            url += '&version=' + new_version;
        }
        xmlhttp.open('GET', url);
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState === 4) {
                if (xmlhttp.status === 200) {
                    try {
                        let res = JSON.parse(xmlhttp.responseText);
                        current_path = new_path;
                        current_is_file = res['storage']['is_file'];
                        current_version = new_version;
                        if (current_is_file) {
                            document.getElementById('fcontent').value = res['storage']['filecontent'];
                            JsonCheck();
                            set_answer(statuses.ok, 'Loaded file ' + new_path + ' version=' + new_version);
                        } else {
                            set_answer(statuses.ok, 'Loaded dir ' + new_path);
                        }
                        fill_dirs(res['storage']['base_path'],
                            res['storage']['parent_path'],
                            res['storage']['tree']);
                        update_buttons(current_is_file);
                        gen_head_link();
                        if (current_is_file) {
                            get_versions(new_path);
                        }
                    } catch(err) {
                        console.log(err);
                        set_answer(statuses.error, 'error on answer parse: ' + err);
                    }
                } else {
                    set_answer(statuses.error, xmlhttp.responseText);
                }
            }
        };
        xmlhttp.send();
    }

    $(document).ready(function() {
        navigate(current_path, -1);
        gen_head_link();
    });
</script>
<body>
<table>
    <tr><td colspan="2"><span id="current-path">path: {{ storage.path }}</span>
        {% if storage.is_frame %}
            <a id="storage-new-window-link"
               href="{% url 'storage' %}?path={{ storage.path }}"
               target="_blank" title="open storage in new window">
                <i class="fa fa-external-link" style="color:green"></i>
            </a>
        {% else %}
            <a id="storage-new-window-link"
               href="{% url 'storage' %}?path={{ storage.path }}"
               title="reset storage path in url">
                <i class="fa fa-external-link" style="color:green"></i>
            </a>
        {% endif %}
    </td></tr>
    <tr>
        <td></td>
        <td><div id="versions"></div></td>
    </tr>
    <tr>
        <td id="navigation_td" style="vertical-align:top">
            <a style="color:brown" href="{% url 'storage' %}?path={{ storage.parent_path }}">..</a><br>
            {% for dir in storage.tree.dirs %}
                <a style="color:brown" href="{% url 'storage' %}?path={{ storage.base_path }}/{{ dir }}">{{ dir }}</a><br>
            {% endfor %}
        <br>
            {% for file in storage.tree.files %}
                <a style="color:green;cursor:pointer;text-decoration: underline"
                   onclick="navigate('{{ storage.base_path }}/{{ file }}', -1)">{{ file }}</a><br>
            {% endfor %}
            Loading...
        </td>
        <td style="vertical-align: top">
            <textarea id='fcontent' cols=100
                      style='float:left;height:400px;width:100%;
                      font-family:"Courier New",Helvetica,Arial,sans-serif'
                      onchange="JsonCheck()"
            >{{ storage.filecontent }}</textarea>

            <div>
                <button onclick="send_file()" id="b_send_file"{% if not storage.is_file %} hidden{% endif %}>Submit</button>
                <span id="format_detect" style="margin-left: 5px"></span>
                    <div style="float:right">
                    <button onclick="switch_element_hidden('storage-create')">create...</button>
                    <button onclick="switch_element_hidden('storage-upload')">upload...</button>
                    <button onclick="switch_fml_element()">fml-copy...</button>
                </div>
            <br>
            <div id="storage-create" hidden style="border:2px solid #fff2b0; padding:5px">
                <label for="create-filename">New file name </label><input id="create-filename" type="text">
                <button onclick="create_file()">Send</button>
            </div>
            <div id="storage-upload" hidden style="border:2px solid #fff2b0; padding:5px">
                <label for="upload-filename">Upload as file</label><input id="upload-filename" type="text">
                <input id="file-to-upload" type='file' onchange="fill_uploaded_filename()">
                <button onclick="upload_file()">Upload</button>
            </div>
            <div id="storage-fml-copy" hidden style="border:2px solid #fff2b0; padding:5px">
                <label for="fml-formula-id">Fml formula id</label><input id="fml-formula-id" type="text">
                <label for="fml-filename">File name</label><input id="fml-filename" type="text">.info-<span id="service-for-fml"></span>
                <button onclick="fetch_fml_file()">Copy</button>
            </div>
            </div>
            <div id="answer" style="padding-left:5px;margin-top:10px;"></div>
        </td>
    </tr>
</table>

<!--properties: is_file is_readable is_json size-->
<!--checkers is_json is_service_folder-->

</body>
</html>
