device-quickpreferences.js 5.35 KB
/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright 2015 Adobe Systems Incorporated
 * All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Adobe Systems Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Adobe Systems Incorporated and its
 * suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Adobe Systems Incorporated.
 */

(function(window, document, $, i18n, dcc) {
    'use strict';

    var PREFERENCES_DIALOG = '#screens-dcc-actions-deveicepreferencces-dialog';
    var PREFERENCES_SELECTOR = '.screens-dashboard-DevicePreferencesTile';
    var TOGGLE_ACTIVATOR = '.screens-DevicePreferenceItem coral-switch';
    var BACKEND_ENDPOINT = '/profile_screens.preferences.json';

    var ui = $(window).adaptTo('foundation-ui');

    function startAsyncOperation(el) {
        ui.wait(el);
        return Promise.resolve();
    }

    function updateProperty(endpoint, property, value) {
        return function() {
            var preferences = {};
            if (typeof property === 'object') {
                preferences = property;
            }
            else {
                preferences[property] = value;
            }
            return $.ajax(endpoint, {
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        data: JSON.stringify(preferences)
                    }
                });
        };
    }

    function sendUpdatePreferencesCommand(deviceId) {
        return function() {
            var lastPing = $('.screens-DevicePing-timestamp').attr('value');
            dcc.playerCommands.sendCommandToDevice(deviceId, dcc.playerCommands.COMMANDS.PREFERENCES_UPDATE);
            return Promise.resolve(lastPing);
        };
    }

    function waitForNextPing(lastPing) {
        return new Promise(function(resolve, reject) {
            var pollForNewPing = function() {
                var ping = $('.screens-DevicePing-timestamp').attr('value');
                if (ping > lastPing) {
                    return resolve();
                }
                window.setTimeout(pollForNewPing, 1000);
            };
            pollForNewPing();
        });
    }

    function reportError(err) {
        ui.notify(null, err, 'error');
        return Promise.resolve();
    }

    function hideDialog() {
        $('.screens-dcc-actions-deveicepreferencces-dialog').get(0).hide();
        return Promise.resolve();
    }

    function endAsyncOperation(el) {
        ui.clearWait();
        return Promise.resolve();
    }

    function reloadUI() {
        var content = $('.foundation-content').adaptTo('foundation-content');
        content.refresh();
    }

    var handleTogglePreference = function(ev) {
        var $device = $(ev.currentTarget).closest('.screens-Device');
        var deviceId = $device.find('[data-device-id]').data('deviceId');
        var devicePath = $device.data('devicePath');

        if (!deviceId) {
            return;
        }

        startAsyncOperation($(ev.target).closest(PREFERENCES_SELECTOR).get(0))
            .then(updateProperty(devicePath + BACKEND_ENDPOINT, ev.target.name, ev.target.checked))
            .then(sendUpdatePreferencesCommand(deviceId))
            .then(waitForNextPing)
            .catch(reportError)
            .then(endAsyncOperation)
            .then(reloadUI);
    };

    var handlePreferencesSubmit = function(ev) {
        var submitPath = ev.target.action;
        var devicePath = submitPath.replace(/^http:\/\/[^/]*/, '').replace(/\/profile_screens.*/, '');
        var deviceId = $('[data-device-path="' + devicePath + '"]').find('[data-device-id]').data('deviceId');

        var prefs = $(PREFERENCES_DIALOG).serializeArray().reduce(function(res, param) {
            if (!param.name.match(/^[_:]/)) {
                res[param.name.split('/').pop()] = param.value;
            }
            return res;
        }, {});

        startAsyncOperation($(PREFERENCES_SELECTOR).get(0))
            .then(updateProperty(devicePath + BACKEND_ENDPOINT, prefs))
            .then(hideDialog)
            .then(sendUpdatePreferencesCommand(deviceId))
            .then(waitForNextPing)
            .catch(reportError)
            .then(endAsyncOperation)
            .then(reloadUI);
        return false;
    };

    $(document).on('change', TOGGLE_ACTIVATOR, handleTogglePreference);

    $(document).on('submit', PREFERENCES_DIALOG, handlePreferencesSubmit);

    // Add cache busting parameter to the dialog src to make sure its data is updated after a modification
    // Remove once GRANITE-14378 has been tackled
    $(document).on('foundation-contentloaded', function(ev) {
        if ($('.screens-DeviceDashboard').length) {
            var $el = $('.screens-dcc-actions-Device-preferences-activator');
            if ($el.length) {
                var action = $el.data('foundationCollectionAction');
                action.data.src = action.data.src.replace(/\?.*/, '') + '?t=' + Date.now();
                $el.data('foundationCollectionAction', action);
            }
        }
    });

}(window, document, Granite.$, Granite.I18n, window.CQ.screens.dcc));