window.onload = function () {
    var app = new Vue({
        el: '#app',
        data: {
        }
    });
};

Vue.component('directory_browser_modal', {
    data: function () {
        return {
            items: "",
            inputName: ""
        };
    },
    template: '<div class="modal fade" id="directoryBrowserModal" tabindex="-1" role="dialog" aria-labelledby="directoryBrowserModalLabel" aria-hidden="true">\
                    <div class= "modal-dialog" role="document" >\
                        <div class="modal-content">\
                            <div class="modal-header">\
                                <h5 class="modal-title">Select Directory</h5>\
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">\
                                    <span aria-hidden="true">&times;</span>\
                                </button>\
                            </div>\
                            <div id="directoryBrowser" class="modal-body">\
                                <p id="directorySelected" class="text-light"></p>\
                                <ul id="directoryChoices" class="list-group">\
                                    <li v-for="(item, index) in items" class="list-group-item"  @click="browseToItem({item})" :key="`{{ item.id }}`"> {{ item.name }}</li>\
                                </ul>\
                            </div>\
                            <div class= "modal-footer">\
                                <button type="button" @click="itemSelected()" class="btn btn-secondary" data-dismiss="modal">OK</button>\
                            </div>\
                        </div>\
                    </div>\
               </div>',
    mounted: function () {        
        var self = this;
        
    },
    methods: {
        browseToItem(args) {
            var self = this;
            var url = 'services/service?method=system.browse&location=' + encodeURIComponent(args.item.id);
            $.getJSON(url, function (data) {
                self.items = data;
            });
            $('#directorySelected').text(args.item.id);
        },

        itemSelected() {
            var self = this;          
            var selectedDirectory = $('#directorySelected').text();
            $(self.inputName).val(selectedDirectory);
            $(self.inputName).trigger("change");
        },

        show(inputName, defaultDirectory) {
            var self = this;
            self.inputName = inputName;

            var url = 'services/service?method=system.browse';
            if (defaultDirectory != null)
                url += "&location=" + defaultDirectory;

            $.getJSON(url, function (data) {
                self.items = data;
            });

            $('#directorySelected').text(defaultDirectory);

            $('#directoryBrowserModal').modal('show');
        }
    }
});