scripts.js 7.57 KB
/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright 2016 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, $, http, i18n, dcc) {
    'use strict';

    var FORM_SELECTOR = '.coral-Form';
    var WIZARD_SELECTOR = FORM_SELECTOR + ' .screens-AssignDeviceWizard';
    var ui = $(window).adaptTo('foundation-ui');

    /**
     * Preselect devices if some are provided as query parameters.
     *
     * FIXME: replace this with advancedselecte initial value once GRANITE-11135 is fixed
     */
    var preselectDevices = function() {

        // Retrieve the devices from the query parameters
        var devices = [];
        window.location.search.substring(1).split('&').forEach(function(paramString) {
            var param = paramString.split('=');
            if (param[0] === 'device') {
                devices.push(window.decodeURIComponent(param[1]));
            }
        });

        // Preselect the devices and advance to the next step
        if (devices.length) {
            devices.forEach(function(devicePath) {
                $('.foundation-collection-item[data-foundation-collection-item-id*="' + devicePath + '"]').get(0).click();
            });
            $(WIZARD_SELECTOR).adaptTo('foundation-wizard').next();
        }
    };

    /**
     * Prefill the device config or display property.
     */
    var prefillDeviceConfigOrDisplay = function() {

        // Retrieve the setting from the query parameters
        var params = window.location.search.substring(1).split('&');
        var deviceConfigParams = params.filter(function(paramString) {
            return paramString.split('=')[0] === 'deviceConfig';
        });
        var displayParams = params.filter(function(paramString) {
            return paramString.split('=')[0] === 'display';
        });

        // We want to always take the last occurence of the parameter
        // and deviceConfigs have precedence over displays
        var parent;
        if (deviceConfigParams.length) {
            parent = window.decodeURIComponent(deviceConfigParams.pop().split('=')[1]);
        }
        else if (displayParams.length) {
            parent = window.decodeURIComponent(displayParams.pop().split('=')[1]);
        }

        // Preselect the devices and advance to the next step
        if (parent) {
            $('[name="display"]').val(parent);
        }
    };

    /**
     * Assign the selected devices to the desired display.
     *
     * @param {jQuery} $wizard  the current wizard
     * @param {Object} resource the target resource for the assignment (display or device config)
     */
    var assignDevices = function($wizard, resource) {

        var devicePath = $('input[name="device"]').val();
        var $deviceItem = $('.foundation-selections-item[data-foundation-collection-item-id="' + devicePath + '"]');
        var deviceId = $deviceItem.find('.foundation-collection-item-title').data('id');
        var display = $('input[name="display"]').val();
        var action = Granite.HTTP.externalize('/api/screens-dcc/devices/' + deviceId);

        var payload = {
            properties: {}
        };

        var deviceConfig = $('input[name="deviceConfig"]').val();
        if (deviceConfig) {
            payload.properties.configPath = deviceConfig;
        } else if (resource.hasResourceType(dcc.constants.RT_DEVICE_CONFIG)) {
            payload.properties.configPath = display;
        } else {
            payload.properties.displayPath = display;
        }

        // Submit the information
        $.ajax({
            type: 'PUT',
            url: action,
            contentType: 'application/json',
            data: JSON.stringify(payload)
        }).done(function(data) {

            dcc.playerCommands.sendCommandToDevice(deviceId, dcc.playerCommands.COMMANDS.CONFIG_UPDATE);

            // Handle the redirection depending on the user's choice
            var handleButton = function(btnId) {
                dcc.navigation.goTo('/screens/dashboard/display.html' + display);
            };

            // Let the user choose what to do next
            ui.prompt(
                i18n.get('Successfully assigned'),
                i18n.get('The device(s) were successfully assigned to the desired display'),
                'success',
                [{
                    id: 'redirect',
                    text: i18n.get('Finish'),
                    primary: true
                }], handleButton);

        }).fail(function(xhr, error, errorThrown) {
            if (error === 'error') {
                ui.alert(
                    i18n.get('Error'),
                    JSON.parse(xhr.responseText).properties['status.message'],
                    'error');
                return;
            }

            ui.alert(error, errorThrown, 'error');
        });
    };

    // Validate the display field
    $(document).on('change', '[name="display"]', function(ev) {
        var $path = $(ev.target);
        dcc.resourceHelper.getResource($path.val() + '/_jcr_content.json')
            .then(function(resource) {
                var isValid = resource.hasResourceType(dcc.constants.RT_DISPLAY) ||
                    resource.hasResourceType(dcc.constants.RT_DEVICE_CONFIG);
                $path.get(0).setCustomValidity(isValid ? '' : i18n.get('Invalid display'));
                $('.foundation-wizard-control[type="submit"]').prop('disabled', !isValid);
            }).catch(function(error) {
                $path.get(0).setCustomValidity(i18n.get('Invalid display: ') + error);
                $('.foundation-wizard-control[type="submit"]').prop('disabled', true);
            });
    });

    // Handle the wizard submission
    $(document).on('submit', FORM_SELECTOR, function(e) {
        if ($(WIZARD_SELECTOR).length) { // FIXME: remove this test once coral2 is dropped
            e.preventDefault();
            var $path = $('input[name="display"]');
            dcc.resourceHelper.getResource($path.val() + '/_jcr_content.json')
                .then(function(resource) {
                    assignDevices($(this), resource);
                }).catch(function(error) {
                    $path.get(0).setCustomValidity(i18n.get('Error: ') + error);
                });
        }
    });

    // Preselect devices and display on page load
    // FIXME: remove this once GRANITE-11135 is fixed
    $(document).one('foundation-selections-change', 'coral-masonry', function() {
        if ($(WIZARD_SELECTOR).length) { // FIXME: remove this test once coral2 is dropped
            // Remove navigation capabilities so we don't trigger a page change when selecting the card in the wizard
            $('[data-foundation-collection-navigator-href]')
                .removeAttr('data-foundation-collection-navigator-href')
                .removeClass('foundation-collection-navigator');
            preselectDevices();
            prefillDeviceConfigOrDisplay();
            var $display = $('[name="display"]');
            if ($display.val()) {
                $display.change();
            }
        }
    });

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