@model Disco.Web.Models.InitialConfig.FileStoreModel
@{
    ViewBag.Title = null;
    Html.BundleDeferred("~/Style/Fancytree");
    Html.BundleDeferred("~/ClientScripts/Modules/jQuery-Fancytree");
}
<h1>@CommonHelpers.Breadcrumbs(Html.ToBreadcrumb("Initial Configuration", MVC.InitialConfig.Index(), "File Store"))</h1>
<div id="initialConfig_FileStore">
    @Html.ValidationSummary(false)

    <div class="form" style="width: 650px">
        <h2>File Store Location</h2>
        <table>
            <tr>
                <td>
                    <div id="treeFilesystem">
                    </div>
                    <div id="treeFilesystemActions">
                        <a id="createDirectory" href="#" class="button" disabled="disabled">Create Directory</a>
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    <div>
                        Selected Location: <span id="locationPath" class="code">&lt;None&gt;</span> <span id="locationPathInvalid" class="smallMessage">(Invalid DataStore Location)</span>
                    </div>
                </td>
            </tr>
        </table>
    </div>
    @using (Html.BeginForm())
    {
        @Html.HiddenFor(m => m.FileStoreLocation)
        <div class="actionBar">
            <input id="submitForm" type="submit" class="button" value="Continue" disabled="disabled" />
        </div>
    }
</div>
<div id="dialogWait" title="Please Wait" class="dialog">
    <h2>
        <i class="fa fa-lg fa-cog fa-spin"></i>
        Building and Validating File Store
    </h2>
    <div>Please wait while the Disco ICT File Store is created and/or validated</div>
</div>
<div id="dialogCreateDirectory" title="Create Directory" class="dialog">
    <h2>Create Directory</h2>
    <input type="text" id="createDirectoryName" />
    <div>Parent: <span id="createDirectoryParent" class="code"></span></div>
</div>
<script>
    (function () {
        var tree = null;
        var $tree = $('#treeFilesystem');
        var $dialogCreateDirectory;
        var fileSystemBranchUrl = '@(Url.Action(MVC.InitialConfig.FileStoreBranch()))';
        var rootNodes = processNode(@(new HtmlString(Json.Encode(Model.DirectoryModel)))).children;

        function processNodes(nodes) {
            return $.map(nodes, processNode);
        }
        function processNode(node) {
            var children = null;
            if (node.SubDirectories) {
                children = $.map(node.SubDirectories, processNode);
            }
            return {
                title: node.IsNew ? node.Name + ' [New]' : node.Name,
                key: node.Path,
                folder: true,
                expanded: !!children,
                unselectable: !node.Selectable,
                tooltip: node.Path,
                children: children,
                lazy: !children
            };
        }

        tree = $tree.fancytree({
            source: rootNodes,
            checkbox: false,
            selectMode: 1,
            keyboard: false,
            lazyload: function (e, data) {
                var node = data.node;
                data.result = {
                    url: fileSystemBranchUrl,
                    data: { Path: node.key },
                    cache: false
                }
            },
            postProcess: function (e, data) {
                data.result = processNode(data.response).children;
            },
            activate: function (e, data) {
                var node = data.node;

                if (node.unselectable) {
                    $('#submitForm').prop('disabled', true);
                    $('#locationPathInvalid').show();
                } else {
                    $('#submitForm').prop('disabled', false);
                    $('#locationPathInvalid').hide();
                }

                $('#createDirectory').prop('disabled', false);
                $('#locationPath').text(node.key);

            }
        }).fancytree('getTree');

        var initalValue = $('#FileStoreLocation').val();
        if (initalValue) {
            var initialNode = tree.getNodeByKey(initalValue);
            if (initialNode) {
                initialNode.setActive(true);
            }
        }

        $('#createDirectory').click(function () {
            if (!$(this).prop('disabled')) {

                // Create Dialog
                if (!$dialogCreateDirectory) {
                    $('#dialogCreateDirectory').dialog({
                        autoOpen: false,
                        draggable: false,
                        modal: true,
                        resizable: false,
                        width: 400,
                        height: 200,
                        buttons: {
                            'Cancel': function () {
                                $('#dialogCreateDirectory').dialog('close');
                            },
                            'Create Directory': function () {
                                var dirName = $('#createDirectoryName').val();
                                if (!!dirName) {
                                    var activeNode = tree.getActiveNode();
                                    if (activeNode) {
                                        var parentPath = activeNode.key;
                                        var path = parentPath.charAt(parentPath.length - 1) === '\\' ? parentPath + dirName : parentPath + '\\' + dirName;
                                        node = {
                                            title: dirName + ' [New]',
                                            key: path,
                                            folder: true,
                                            expanded: false,
                                            unselectable: false,
                                            tooltip: path,
                                            lazy: false
                                        }
                                        activeNode.addNode(node).setActive(true);
                                    }
                                }
                                $('#dialogCreateDirectory').dialog('close');
                            }
                        }
                    })
                }

                var activeNode = tree.getActiveNode();
                if (activeNode) {
                    $('#dialogCreateDirectory').dialog('open');
                    $('#createDirectoryName').val('').focus();
                    $('#createDirectoryParent').text(activeNode.key);
                }

                return false;
            }
        });

        $('#submitForm').closest('form').submit(function () {
            var activeNode = tree.getActiveNode();
            if (activeNode && !activeNode.unselectable) {
                $('#FileStoreLocation').val(activeNode.key);
                if ($(this).valid()) {
                    $('#dialogWait').dialog({
                        autoOpen: true,
                        draggable: false,
                        modal: true,
                        resizable: false,
                        width: 400,
                        height: 150,
                        closeOnEscape: false
                    }).closest('.ui-dialog').find('.ui-dialog-titlebar-close').hide();
                }
                return true;
            } else {
                alert('Invalid FileStore Location');
                return false;
            }
        });
    })();
</script>
