define(['jQuery', 'loading', 'libraryMenu', 'globalize'], function ($, loading, libraryMenu, globalize) {
    'use strict';

    function triggerChange(select) {
        var evt = document.createEvent('HTMLEvents');
        evt.initEvent('change', false, true);
        select.dispatchEvent(evt);
    }

    function loadMediaFolders(page, user, mediaFolders) {
        var html = '';
        html += '<h3 class="checkboxListLabel">' + globalize.translate('HeaderLibraries') + '</h3>';
        html += '<div class="checkboxList paperList checkboxList-paperList">';

        for (var i = 0, length = mediaFolders.length; i < length; i++) {
            var folder = mediaFolders[i];
            var isChecked = user.Policy.EnableAllFolders || -1 != user.Policy.EnabledFolders.indexOf(folder.Id);
            var checkedAttribute = isChecked ? ' checked="checked"' : '';
            html += '<label><input type="checkbox" is="emby-checkbox" class="chkFolder" data-id="' + folder.Id + '" ' + checkedAttribute + '><span>' + folder.Name + '</span></label>';
        }

        html += '</div>';
        page.querySelector('.folderAccess').innerHTML = html;
        var chkEnableAllFolders = page.querySelector('#chkEnableAllFolders');
        chkEnableAllFolders.checked = user.Policy.EnableAllFolders;
        triggerChange(chkEnableAllFolders);
    }

    function loadChannels(page, user, channels) {
        var html = '';
        html += '<h3 class="checkboxListLabel">' + globalize.translate('HeaderChannels') + '</h3>';
        html += '<div class="checkboxList paperList checkboxList-paperList">';

        for (var i = 0, length = channels.length; i < length; i++) {
            var folder = channels[i];
            var isChecked = user.Policy.EnableAllChannels || -1 != user.Policy.EnabledChannels.indexOf(folder.Id);
            var checkedAttribute = isChecked ? ' checked="checked"' : '';
            html += '<label><input type="checkbox" is="emby-checkbox" class="chkChannel" data-id="' + folder.Id + '" ' + checkedAttribute + '><span>' + folder.Name + '</span></label>';
        }

        html += '</div>';
        $('.channelAccess', page).show().html(html);

        if (channels.length) {
            $('.channelAccessContainer', page).show();
        } else {
            $('.channelAccessContainer', page).hide();
        }

        $('#chkEnableAllChannels', page).prop('checked', user.Policy.EnableAllChannels);
    }

    function loadDevices(page, user, devices) {
        var html = '';
        html += '<h3 class="checkboxListLabel">' + globalize.translate('HeaderDevices') + '</h3>';
        html += '<div class="checkboxList paperList checkboxList-paperList">';

        for (var i = 0, length = devices.length; i < length; i++) {
            var device = devices[i];
            var checkedAttribute = user.Policy.EnableAllDevices || -1 != user.Policy.EnabledDevices.indexOf(device.Id) ? ' checked="checked"' : '';
            html += '<label><input type="checkbox" is="emby-checkbox" class="chkDevice" data-id="' + device.Id + '" ' + checkedAttribute + '><span>' + device.Name + ' - ' + device.AppName + '</span></label>';
        }

        html += '</div>';
        $('.deviceAccess', page).show().html(html);
        $('#chkEnableAllDevices', page).prop('checked', user.Policy.EnableAllDevices);

        if (user.Policy.IsAdministrator) {
            page.querySelector('.deviceAccessContainer').classList.add('hide');
        } else {
            page.querySelector('.deviceAccessContainer').classList.remove('hide');
        }
    }

    function loadUser(page, user, loggedInUser, mediaFolders, channels, devices) {
        page.querySelector('.username').innerHTML = user.Name;
        libraryMenu.setTitle(user.Name);
        loadChannels(page, user, channels);
        loadMediaFolders(page, user, mediaFolders);
        loadDevices(page, user, devices);
        loading.hide();
    }

    function onSaveComplete(page) {
        loading.hide();

        require(['toast'], function (toast) {
            toast(globalize.translate('SettingsSaved'));
        });
    }

    function saveUser(user, page) {
        user.Policy.EnableAllFolders = $('#chkEnableAllFolders', page).is(':checked');
        user.Policy.EnabledFolders = user.Policy.EnableAllFolders ? [] : $('.chkFolder', page).get().filter(function (c) {
            return c.checked;
        }).map(function (c) {
            return c.getAttribute('data-id');
        });
        user.Policy.EnableAllChannels = $('#chkEnableAllChannels', page).is(':checked');
        user.Policy.EnabledChannels = user.Policy.EnableAllChannels ? [] : $('.chkChannel', page).get().filter(function (c) {
            return c.checked;
        }).map(function (c) {
            return c.getAttribute('data-id');
        });
        user.Policy.EnableAllDevices = $('#chkEnableAllDevices', page).is(':checked');
        user.Policy.EnabledDevices = user.Policy.EnableAllDevices ? [] : $('.chkDevice', page).get().filter(function (c) {
            return c.checked;
        }).map(function (c) {
            return c.getAttribute('data-id');
        });
        user.Policy.BlockedChannels = null;
        user.Policy.BlockedMediaFolders = null;
        ApiClient.updateUserPolicy(user.Id, user.Policy).then(function () {
            onSaveComplete(page);
        });
    }

    function onSubmit() {
        var page = $(this).parents('.page');
        loading.show();
        var userId = getParameterByName('userId');
        ApiClient.getUser(userId).then(function (result) {
            saveUser(result, page);
        });
        return false;
    }

    $(document).on('pageinit', '#userLibraryAccessPage', function () {
        var page = this;
        $('#chkEnableAllDevices', page).on('change', function () {
            if (this.checked) {
                $('.deviceAccessListContainer', page).hide();
            } else {
                $('.deviceAccessListContainer', page).show();
            }
        });
        $('#chkEnableAllChannels', page).on('change', function () {
            if (this.checked) {
                $('.channelAccessListContainer', page).hide();
            } else {
                $('.channelAccessListContainer', page).show();
            }
        });
        page.querySelector('#chkEnableAllFolders').addEventListener('change', function () {
            if (this.checked) {
                page.querySelector('.folderAccessListContainer').classList.add('hide');
            } else {
                page.querySelector('.folderAccessListContainer').classList.remove('hide');
            }
        });
        $('.userLibraryAccessForm').off('submit', onSubmit).on('submit', onSubmit);
    }).on('pageshow', '#userLibraryAccessPage', function () {
        var page = this;
        loading.show();
        var promise1;
        var userId = getParameterByName('userId');

        if (userId) {
            promise1 = ApiClient.getUser(userId);
        } else {
            var deferred = $.Deferred();
            deferred.resolveWith(null, [{
                Configuration: {}
            }]);
            promise1 = deferred.promise();
        }

        var promise2 = Dashboard.getCurrentUser();
        var promise4 = ApiClient.getJSON(ApiClient.getUrl('Library/MediaFolders', {
            IsHidden: false
        }));
        var promise5 = ApiClient.getJSON(ApiClient.getUrl('Channels'));
        var promise6 = ApiClient.getJSON(ApiClient.getUrl('Devices'));
        Promise.all([promise1, promise2, promise4, promise5, promise6]).then(function (responses) {
            loadUser(page, responses[0], responses[1], responses[2].Items, responses[3].Items, responses[4].Items);
        });
    });
});
