<commit_before>define([
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/_base/array',
    'dojo/topic',

    'esri/config',
    'esri/units',
    'dojo/number',
    'esri/tasks/query',
    'esri/tasks/RelationshipQuery',
    'esri/tasks/QueryTask',
    'esri/geometry/Point',
    'esri/geometry/Multipoint',
    'esri/geometry/Polyline',
    'esri/geometry/Polygon',
    'esri/geometry/Extent',
    'esri/geometry/geometryEngine',
    'esri/tasks/BufferParameters'

], function (
    declare,
    lang,
    array,
    topic,

    esriConfig,
    units,
    num,
    Query,
    RelationshipQuery,
    QueryTask,
    Point,
    Multipoint,
    Polyline,
    Polygon,
    Extent,
    geometryEngine,
    BufferParameters
) {

    return declare(null, {

        results: null,

        queryOptions: {},

        // for all the standard parameters, see for https://developers.arcgis.com/javascript/jsapi/query-amd.html
        defaultQueryOptions: {
            queryParameters: {
                type: 'spatial',
                outputSpatialReference: 4326,
                url: null,
                layerID: null,
                sublayerID: null,
                objectIDs: null,
                outFields: ['*'],
                where: '1=1',
                addToExisting: false,
                geometry: null,
                distance: null,
                start: null,
                num: null,
                text: null,
                timeExtent: null,
                units: 'feet',
                geometryPrecision: null,
                groupByFieldsForStatistics: null,
                orderByFields: null,
                outStatistics: null,
                pixelSize: null,
                relationParam: null,
                spatialRelationship: Query.SPATIAL_REL_INTERSECTS,
                includeLayerDefinitions: false
            },

            // provide the parameters if there is a spatial query linked from a table/database query
            linkedQuery: {
                url: null,
                layerID: null,
                sublayerID: null,
                linkField: null,
                idProperty: null,
                linkIDs: [] // if linkedQuery, then store the linkedIDs for use in linked query
            },

            // allow a buffer to be performed before a spatial
            // query and then use the buffer geometry in the query
            // if showOnly = true, the buffer is displayed  but
            // the query is not run
            bufferParameters: {
                distance: null,
                unit: null,
                geodesic: true,
                showOnly: false
            },

            // executing a linked query?
            isLinkedQuery: false,

            // used for linkedQueries
            linkField: null,

            // default Unique ID
            // if null, will attempt to get a field of
            // type 'esriFieldTypeOID' from the results
            idProperty: null

        },

        isLinkedQuery: false,

        getQueryConfiguration: function (options) {
            options = this.mixinDeep(lang.clone(this.defaultQueryOptions), options);

            this.queryParameters = options.queryParameters;
            this.bufferParameters = options.bufferParameters;
            this.idProperty = options.idProperty;

            this.linkField = options.linkField;
            this.linkedQuery = options.linkedQuery;
            this.isLinkedQuery = false;
        },

        executeQueryTask: function (options) {
            this.getConfiguration(options);
            if (this.executingQuery === true) {
                return;
            }

            // grab the query parameters
            if (options && options.queryOptions && options.queryOptions.queryParameters) {
                this.queryParameters = options.queryOptions.queryParameters;
            }

            var qp = this.queryParameters;

            // only clear everything when we want to preserve the previous results
            if (qp.addToExisting !== true && !qp.bufferGeometry) {
                this.clearAll();
            }

            this.getConfiguration(options);
            qp = this.queryParameters;

            if (qp.addToExisting !== true) {
                this.clearFeatures();
            }
            this.clearSelectedFeatures();
            if ((qp.addToExisting !== true) && (this.isLinkedQuery !== true || this.type === 'table') && (this.bufferParameters && !this.bufferParameters.showOnly)) {
                this.clearGrid();
            }

            if (qp.geometry) {
                qp.geometry = this.createGeometry(qp.geometry);
            }

            if (this.featureOptions.buffer && this.bufferParameters && this.bufferParameters.distance) {
                this.executeBuffer();
                return;
            }
            this.featureOptions.buffer = false;

            var url = this.getQueryTaskURL();
            if (!url) {
                return;
            }

            this.executingQuery = true;
            var qt = new QueryTask(url);
            var q = this.buildQueryFromParameters(qp);

            if (this.growlOptions.loading && !this.isLinkedQuery) {
                this.growlID = this.topicID + 'Growl-StartSearch';
                var msg = lang.mixin(this.i18n.messages.searching, {
                    id: this.growlID,
                    timeout: (esriConfig.defaults.io.timeout + 5000),
                    showProgressBar: true
                });
                topic.publish('growler/growl', msg);
            }

            if (qp.type === 'relationship') {
                qt.executeRelationshipQuery(q, lang.hitch(this, 'processQueryResults'), lang.hitch(this, 'processQueryError'));
            } else {
                qt.execute(q, lang.hitch(this, 'processQueryResults'), lang.hitch(this, 'processQueryError'));
            }
        },

        buildQueryFromParameters: function (qp) {
            var q = null;
            if (qp.type === 'relationship') {
                q = new RelationshipQuery();
            } else {
                q = new Query();
            }

            q.geometryPrecision = qp.geometryPrecision;
            q.maxAllowableOffset = qp.maxAllowableOffset;
            q.objectIds = qp.objectIDs;
            q.outFields = qp.outFields;
            q.outSpatialReference = qp.outSpatialReference || this.map.spatialReference;
            q.returnGeometry = this.featureOptions.features;
            q.where = qp.where;

            if (qp.type === 'spatial') {
                q.distance = qp.distance;
                q.geometry = qp.bufferGeometry || qp.geometry;
                q.groupByFieldsForStatistics = qp.groupByFieldsForStatistics;
                q.num = qp.num;
                q.orderByFields = qp.orderByFields;
                q.outStatistics = qp.outStatistics;
                q.pixelSize = qp.pixelSize;
                q.relationParam = qp.relationParam;
                q.spatialRelationship = qp.spatialRelationship;
                q.start = qp.start;
                q.text = qp.text;
                q.timeExtent = qp.timeExtent;
                q.units = qp.units;

            } else if (qp.type === 'relationship') {
                q.definitionExpression = qp.definitionExpression;
                q.relationshipId = qp.relationshipID;
            }
            return q;
        },

        executeLinkedQuery: function (lq) {
            var qp = this.queryParameters;
            var linkField = lq.linkField || this.linkField;
            var type = lq.type || 'spatial';
            lq.type = type;

            if (!lq.linkIDs) {
                return;
            }
            lq.where = linkField + ' IN (' + lq.linkIDs.splice(',') + ')';
            delete lq.linkedIDs;

            if (!lq.outFields) {
                lq.outFields = [];
            }
            if (lq.returnGeometry !== false && (type === 'spatial')) {
                lq.returnGeometry = true;
            }
            if (!lq.distance && qp.distance) {
                lq.distance = qp.distance;
            }
            if (!lq.units && qp.units) {
                lq.units = qp.units;
            }
            if (!lq.geometry && qp.geometry) {
                lq.geometry = qp.geometry;
            }
            if (!lq.spatialRelationship && qp.spatialRelationship) {
                lq.spatialRelationship = qp.spatialRelationship;
            }

            this.executeQueryTask({
                queryOptions: {
                    queryParameters: lq,
                    isLinkedQuery: true
                }
            });
        },

        executeBuffer: function () {
            this.clearBufferGraphics();

            // experimental use of geometryEngine
            if (this.map.spatialReference.wkid === 4326 || this.map.spatialReference.wkid === 102100) {
                var geometries = geometryEngine.geodesicBuffer(this.queryParameters.geometry, this.bufferParameters.distance, (this.bufferParameters.unit || units.FEET));
                this.processBufferQueryResults([geometries]);
            } else {
                var buffParams = new BufferParameters();
                buffParams.geometries = [this.queryParameters.geometry];
                buffParams.distances = [this.bufferParameters.distance];
                buffParams.unit = this.bufferParameters.unit || units.FEET;
                buffParams.geodesic = this.bufferParameters.geodesic || true;
                buffParams.bufferSpatialReference = this.map.spatialReference;
                buffParams.outSpatialReference = this.map.spatialReference;

                esriConfig.defaults.geometryService.buffer(buffParams, lang.hitch(this, 'processBufferQueryResults'));
            }
        },

        refreshQueryTask: function () {
            this.executeQueryTask(this.queryOptions);
        },

        processQueryError: function (error) {
            this.clearGrowl();
            this.executingQuery = false;

            var msg = lang.mixin(this.i18n.messages.searchError, {
                level: 'error',
                timeout: 5000
            });
            topic.publish('growler/growl', msg);
            topic.publish('viewer/handleError', {
                error: error
            });
        },

        processQueryResults: function (results) {
            this.clearGrowl();
            this.executingQuery = false;

            if (!results) {
                return;
            }

            var originalRecs = this.getFeatureCount();
            this.results = results;
            this.getFeaturesFromResults();

            if (!this.idProperty) {
                this.getIdProperty(results);
            }

            var recCount = this.getFeatureCount();
            var newRecs = (originalRecs === 0) ? 0 : recCount - originalRecs;
            var msgNls = this.i18n.messages.searchResults;
            var msg = msgNls.message;
            if (!msg) {
                if (recCount > 0) {
                    msg = '';
                    if (newRecs > 0) {
                        msg += num.format(newRecs) + ' ' + msgNls.newFeatures + ' ';
                        msg += (newRecs > 1) ? msgNls.features : msgNls.feature;
                        msg += ' ' + msgNls.found + '.<br/>';
                    }
                    msg += num.format(recCount) + ' ';
                    msg += (recCount > 1) ? msgNls.features : msgNls.feature;
                    msg += ' ' + msgNls.found;
                    msg += (newRecs > 0) ? ' ' + msgNls.total + '.' : '.';
                } else {
                    msg = msgNls.noFeatures;
                }
            }

            if (recCount > 0) {
                if (this.featureOptions.source && this.queryParameters.geometry) {
                    this.addSourceGraphic(this.queryParameters.geometry);
                }
                this.populateGrid(results);
            }

            if (this.growlOptions.results && !this.isLinkedQuery) {

                topic.publish('growler/growl', {
                    title: this.title + ' ' + msgNls.title,
                    message: msg,
                    level: 'default',
                    timeout: 5000
                });
            }

            topic.publish(this.topicID + '/queryResults', this.results);
            topic.publish(this.attributesContainerID + '/openPane');
            topic.publish(this.attributesContainerID + '/tableUpdated', this);

            if (this.linkedQuery && (this.linkedQuery.url || this.linkedQuery.layerID)) {
                var lq = lang.clone(this.linkedQuery);
                this.executeLinkedQuery(lq);
            } else {
                this.isLinkedQuery = false;
            }

            this.queryParametersType = 'spatial';
            this.linkedQuery = {
                url: null,
                linkIDs: []
            };
        },

        processBufferQueryResults: function (geometries) {
            var showOnly = this.bufferParameters.showOnly;

            // reset the buffer
            this.bufferParameters = lang.clone(this.defaultQueryOptions.bufferParameters);

            if (geometries && geometries.length > 0) {
                this.addBufferGraphic(geometries[0]);

                if (showOnly !== true) {
                    if (this.queryParameters) {
                        this.queryParameters.geometry = this.geometryToJson(this.queryParameters.geometry);
                    }
                    var qParams = lang.clone(this.queryParameters);
                    qParams.bufferGeometry = geometries[0];

                    this.executeQueryTask({
                        queryOptions: {
                            queryParameters: qParams,
                            bufferParameters: this.bufferParameters,
                            linkedQuery: this.linkedQuery,
                            linkField: this.linkField,
                            isLinkedQuery: this.isLinkedQuery
                        }
                    });

                } else if (this.featureOptions.source) {
                    this.addSourceGraphic(this.queryParameters.geometry);
                    this.zoomToBufferGraphics();
                }
            }
        },

        // convert geometry to Json to avoid issues when cloning
        geometryToJson: function (geom) {
            if (geom && geom.type && geom.toJson) {
                var type = geom.type;
                geom = geom.toJson();
                geom.type = type;
            }
            return geom;
        },

        // allow geometry to come as Json or a geometry type
        createGeometry: function (geom) {
            var type = geom.type;
            if (geom.toJson) {
                geom = geom.toJson();
            }
            switch (type) {
            case 'point':
                return new Point(geom);
            case 'multipoint':
                return new Multipoint(geom);
            case 'polyline':
                return new Polyline(geom);
            case 'polygon':
                return new Polygon(geom);
            case 'extent':
                return new Extent(geom);
            default:
                geom.type = type;
                return geom;
            }
        },

        getQueryResults: function () {
            return this.results;
        },

        clearQueryResults: function () {
            this.results = null;
        },

        hasLinkedQuery: function () {
            var lq = this.linkedQuery;
            if (this.linkField && lq && lq.linkField) {
                if (!lq.linkIDs) {
                    lq.linkIDs = [];
                }
                return true;
            }
            return false;
        },

        // get the idProperty from an 'esriFieldTypeOID'
        // type of field (if available) in the results
        getIdProperty: function (results) {
            var fields = results.fields;
            if (fields && fields.length > 0) {
                array.forEach(fields, lang.hitch(this, function (field) {
                    if (field.type === 'esriFieldTypeOID') {
                        this.idProperty = field.name;
                    }
                }));
            }
        },

        getQueryTaskURL: function () {
            var qp = this.queryParameters;
            var url = qp.url;
            if (!url && qp.layerID) {
                var layer = this.map.getLayer(qp.layerID);
                if (layer) {
                    var whereByLayerDef;
                    if (layer.declaredClass === 'esri.layers.FeatureLayer') { // Feature Layer
                        whereByLayerDef = layer.getDefinitionExpression();

                        url = layer.url;
                    } else if (layer.declaredClass === 'esri.layers.ArcGISDynamicMapServiceLayer') { // Dynamic Layer
                        whereByLayerDef = layer.layerDefinitions[qp.sublayerID];

                        if (qp.sublayerID !== null) {
                            url = layer.url + '/' + qp.sublayerID;
                        } else if (layer.visibleLayers && layer.visibleLayers.length === 1) {
                            url = layer.url + '/' + layer.visibleLayers[0];
                        }
                    }

                    if (whereByLayerDef && qp.includeLayerDefinitions) {
                        if (qp.where) {
                            qp.where = '(' + whereByLayerDef + ') AND (' + qp.where + ')';
                        } else {
                            qp.where = whereByLayerDef;
                        }
                    }
                }
            }
            return url;
        }
    });
});
<commit_msg>Fix bug if layerDefinitions is not defined<commit_after>define([
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/_base/array',
    'dojo/topic',

    'esri/config',
    'esri/units',
    'dojo/number',
    'esri/tasks/query',
    'esri/tasks/RelationshipQuery',
    'esri/tasks/QueryTask',
    'esri/geometry/Point',
    'esri/geometry/Multipoint',
    'esri/geometry/Polyline',
    'esri/geometry/Polygon',
    'esri/geometry/Extent',
    'esri/geometry/geometryEngine',
    'esri/tasks/BufferParameters'

], function (
    declare,
    lang,
    array,
    topic,

    esriConfig,
    units,
    num,
    Query,
    RelationshipQuery,
    QueryTask,
    Point,
    Multipoint,
    Polyline,
    Polygon,
    Extent,
    geometryEngine,
    BufferParameters
) {

    return declare(null, {

        results: null,

        queryOptions: {},

        // for all the standard parameters, see for https://developers.arcgis.com/javascript/jsapi/query-amd.html
        defaultQueryOptions: {
            queryParameters: {
                type: 'spatial',
                outputSpatialReference: 4326,
                url: null,
                layerID: null,
                sublayerID: null,
                objectIDs: null,
                outFields: ['*'],
                where: '1=1',
                addToExisting: false,
                geometry: null,
                distance: null,
                start: null,
                num: null,
                text: null,
                timeExtent: null,
                units: 'feet',
                geometryPrecision: null,
                groupByFieldsForStatistics: null,
                orderByFields: null,
                outStatistics: null,
                pixelSize: null,
                relationParam: null,
                spatialRelationship: Query.SPATIAL_REL_INTERSECTS,
                includeLayerDefinitions: false
            },

            // provide the parameters if there is a spatial query linked from a table/database query
            linkedQuery: {
                url: null,
                layerID: null,
                sublayerID: null,
                linkField: null,
                idProperty: null,
                linkIDs: [] // if linkedQuery, then store the linkedIDs for use in linked query
            },

            // allow a buffer to be performed before a spatial
            // query and then use the buffer geometry in the query
            // if showOnly = true, the buffer is displayed  but
            // the query is not run
            bufferParameters: {
                distance: null,
                unit: null,
                geodesic: true,
                showOnly: false
            },

            // executing a linked query?
            isLinkedQuery: false,

            // used for linkedQueries
            linkField: null,

            // default Unique ID
            // if null, will attempt to get a field of
            // type 'esriFieldTypeOID' from the results
            idProperty: null

        },

        isLinkedQuery: false,

        getQueryConfiguration: function (options) {
            options = this.mixinDeep(lang.clone(this.defaultQueryOptions), options);

            this.queryParameters = options.queryParameters;
            this.bufferParameters = options.bufferParameters;
            this.idProperty = options.idProperty;

            this.linkField = options.linkField;
            this.linkedQuery = options.linkedQuery;
            this.isLinkedQuery = false;
        },

        executeQueryTask: function (options) {
            this.getConfiguration(options);
            if (this.executingQuery === true) {
                return;
            }

            // grab the query parameters
            if (options && options.queryOptions && options.queryOptions.queryParameters) {
                this.queryParameters = options.queryOptions.queryParameters;
            }

            var qp = this.queryParameters;

            // only clear everything when we want to preserve the previous results
            if (qp.addToExisting !== true && !qp.bufferGeometry) {
                this.clearAll();
            }

            this.getConfiguration(options);
            qp = this.queryParameters;

            if (qp.addToExisting !== true) {
                this.clearFeatures();
            }
            this.clearSelectedFeatures();
            if ((qp.addToExisting !== true) && (this.isLinkedQuery !== true || this.type === 'table') && (this.bufferParameters && !this.bufferParameters.showOnly)) {
                this.clearGrid();
            }

            if (qp.geometry) {
                qp.geometry = this.createGeometry(qp.geometry);
            }

            if (this.featureOptions.buffer && this.bufferParameters && this.bufferParameters.distance) {
                this.executeBuffer();
                return;
            }
            this.featureOptions.buffer = false;

            var url = this.getQueryTaskURL();
            if (!url) {
                return;
            }

            this.executingQuery = true;
            var qt = new QueryTask(url);
            var q = this.buildQueryFromParameters(qp);

            if (this.growlOptions.loading && !this.isLinkedQuery) {
                this.growlID = this.topicID + 'Growl-StartSearch';
                var msg = lang.mixin(this.i18n.messages.searching, {
                    id: this.growlID,
                    timeout: (esriConfig.defaults.io.timeout + 5000),
                    showProgressBar: true
                });
                topic.publish('growler/growl', msg);
            }

            if (qp.type === 'relationship') {
                qt.executeRelationshipQuery(q, lang.hitch(this, 'processQueryResults'), lang.hitch(this, 'processQueryError'));
            } else {
                qt.execute(q, lang.hitch(this, 'processQueryResults'), lang.hitch(this, 'processQueryError'));
            }
        },

        buildQueryFromParameters: function (qp) {
            var q = null;
            if (qp.type === 'relationship') {
                q = new RelationshipQuery();
            } else {
                q = new Query();
            }

            q.geometryPrecision = qp.geometryPrecision;
            q.maxAllowableOffset = qp.maxAllowableOffset;
            q.objectIds = qp.objectIDs;
            q.outFields = qp.outFields;
            q.outSpatialReference = qp.outSpatialReference || this.map.spatialReference;
            q.returnGeometry = this.featureOptions.features;
            q.where = qp.where;

            if (qp.type === 'spatial') {
                q.distance = qp.distance;
                q.geometry = qp.bufferGeometry || qp.geometry;
                q.groupByFieldsForStatistics = qp.groupByFieldsForStatistics;
                q.num = qp.num;
                q.orderByFields = qp.orderByFields;
                q.outStatistics = qp.outStatistics;
                q.pixelSize = qp.pixelSize;
                q.relationParam = qp.relationParam;
                q.spatialRelationship = qp.spatialRelationship;
                q.start = qp.start;
                q.text = qp.text;
                q.timeExtent = qp.timeExtent;
                q.units = qp.units;

            } else if (qp.type === 'relationship') {
                q.definitionExpression = qp.definitionExpression;
                q.relationshipId = qp.relationshipID;
            }
            return q;
        },

        executeLinkedQuery: function (lq) {
            var qp = this.queryParameters;
            var linkField = lq.linkField || this.linkField;
            var type = lq.type || 'spatial';
            lq.type = type;

            if (!lq.linkIDs) {
                return;
            }
            lq.where = linkField + ' IN (' + lq.linkIDs.splice(',') + ')';
            delete lq.linkedIDs;

            if (!lq.outFields) {
                lq.outFields = [];
            }
            if (lq.returnGeometry !== false && (type === 'spatial')) {
                lq.returnGeometry = true;
            }
            if (!lq.distance && qp.distance) {
                lq.distance = qp.distance;
            }
            if (!lq.units && qp.units) {
                lq.units = qp.units;
            }
            if (!lq.geometry && qp.geometry) {
                lq.geometry = qp.geometry;
            }
            if (!lq.spatialRelationship && qp.spatialRelationship) {
                lq.spatialRelationship = qp.spatialRelationship;
            }

            this.executeQueryTask({
                queryOptions: {
                    queryParameters: lq,
                    isLinkedQuery: true
                }
            });
        },

        executeBuffer: function () {
            this.clearBufferGraphics();

            // experimental use of geometryEngine
            if (this.map.spatialReference.wkid === 4326 || this.map.spatialReference.wkid === 102100) {
                var geometries = geometryEngine.geodesicBuffer(this.queryParameters.geometry, this.bufferParameters.distance, (this.bufferParameters.unit || units.FEET));
                this.processBufferQueryResults([geometries]);
            } else {
                var buffParams = new BufferParameters();
                buffParams.geometries = [this.queryParameters.geometry];
                buffParams.distances = [this.bufferParameters.distance];
                buffParams.unit = this.bufferParameters.unit || units.FEET;
                buffParams.geodesic = this.bufferParameters.geodesic || true;
                buffParams.bufferSpatialReference = this.map.spatialReference;
                buffParams.outSpatialReference = this.map.spatialReference;

                esriConfig.defaults.geometryService.buffer(buffParams, lang.hitch(this, 'processBufferQueryResults'));
            }
        },

        refreshQueryTask: function () {
            this.executeQueryTask(this.queryOptions);
        },

        processQueryError: function (error) {
            this.clearGrowl();
            this.executingQuery = false;

            var msg = lang.mixin(this.i18n.messages.searchError, {
                level: 'error',
                timeout: 5000
            });
            topic.publish('growler/growl', msg);
            topic.publish('viewer/handleError', {
                error: error
            });
        },

        processQueryResults: function (results) {
            this.clearGrowl();
            this.executingQuery = false;

            if (!results) {
                return;
            }

            var originalRecs = this.getFeatureCount();
            this.results = results;
            this.getFeaturesFromResults();

            if (!this.idProperty) {
                this.getIdProperty(results);
            }

            var recCount = this.getFeatureCount();
            var newRecs = (originalRecs === 0) ? 0 : recCount - originalRecs;
            var msgNls = this.i18n.messages.searchResults;
            var msg = msgNls.message;
            if (!msg) {
                if (recCount > 0) {
                    msg = '';
                    if (newRecs > 0) {
                        msg += num.format(newRecs) + ' ' + msgNls.newFeatures + ' ';
                        msg += (newRecs > 1) ? msgNls.features : msgNls.feature;
                        msg += ' ' + msgNls.found + '.<br/>';
                    }
                    msg += num.format(recCount) + ' ';
                    msg += (recCount > 1) ? msgNls.features : msgNls.feature;
                    msg += ' ' + msgNls.found;
                    msg += (newRecs > 0) ? ' ' + msgNls.total + '.' : '.';
                } else {
                    msg = msgNls.noFeatures;
                }
            }

            if (recCount > 0) {
                if (this.featureOptions.source && this.queryParameters.geometry) {
                    this.addSourceGraphic(this.queryParameters.geometry);
                }
                this.populateGrid(results);
            }

            if (this.growlOptions.results && !this.isLinkedQuery) {

                topic.publish('growler/growl', {
                    title: this.title + ' ' + msgNls.title,
                    message: msg,
                    level: 'default',
                    timeout: 5000
                });
            }

            topic.publish(this.topicID + '/queryResults', this.results);
            topic.publish(this.attributesContainerID + '/openPane');
            topic.publish(this.attributesContainerID + '/tableUpdated', this);

            if (this.linkedQuery && (this.linkedQuery.url || this.linkedQuery.layerID)) {
                var lq = lang.clone(this.linkedQuery);
                this.executeLinkedQuery(lq);
            } else {
                this.isLinkedQuery = false;
            }

            this.queryParametersType = 'spatial';
            this.linkedQuery = {
                url: null,
                linkIDs: []
            };
        },

        processBufferQueryResults: function (geometries) {
            var showOnly = this.bufferParameters.showOnly;

            // reset the buffer
            this.bufferParameters = lang.clone(this.defaultQueryOptions.bufferParameters);

            if (geometries && geometries.length > 0) {
                this.addBufferGraphic(geometries[0]);

                if (showOnly !== true) {
                    if (this.queryParameters) {
                        this.queryParameters.geometry = this.geometryToJson(this.queryParameters.geometry);
                    }
                    var qParams = lang.clone(this.queryParameters);
                    qParams.bufferGeometry = geometries[0];

                    this.executeQueryTask({
                        queryOptions: {
                            queryParameters: qParams,
                            bufferParameters: this.bufferParameters,
                            linkedQuery: this.linkedQuery,
                            linkField: this.linkField,
                            isLinkedQuery: this.isLinkedQuery
                        }
                    });

                } else if (this.featureOptions.source) {
                    this.addSourceGraphic(this.queryParameters.geometry);
                    this.zoomToBufferGraphics();
                }
            }
        },

        // convert geometry to Json to avoid issues when cloning
        geometryToJson: function (geom) {
            if (geom && geom.type && geom.toJson) {
                var type = geom.type;
                geom = geom.toJson();
                geom.type = type;
            }
            return geom;
        },

        // allow geometry to come as Json or a geometry type
        createGeometry: function (geom) {
            var type = geom.type;
            if (geom.toJson) {
                geom = geom.toJson();
            }
            switch (type) {
            case 'point':
                return new Point(geom);
            case 'multipoint':
                return new Multipoint(geom);
            case 'polyline':
                return new Polyline(geom);
            case 'polygon':
                return new Polygon(geom);
            case 'extent':
                return new Extent(geom);
            default:
                geom.type = type;
                return geom;
            }
        },

        getQueryResults: function () {
            return this.results;
        },

        clearQueryResults: function () {
            this.results = null;
        },

        hasLinkedQuery: function () {
            var lq = this.linkedQuery;
            if (this.linkField && lq && lq.linkField) {
                if (!lq.linkIDs) {
                    lq.linkIDs = [];
                }
                return true;
            }
            return false;
        },

        // get the idProperty from an 'esriFieldTypeOID'
        // type of field (if available) in the results
        getIdProperty: function (results) {
            var fields = results.fields;
            if (fields && fields.length > 0) {
                array.forEach(fields, lang.hitch(this, function (field) {
                    if (field.type === 'esriFieldTypeOID') {
                        this.idProperty = field.name;
                    }
                }));
            }
        },

        getQueryTaskURL: function () {
            var qp = this.queryParameters;
            var url = qp.url;
            if (!url && qp.layerID) {
                var layer = this.map.getLayer(qp.layerID);
                if (layer) {
                    var whereByLayerDef;
                    if (layer.declaredClass === 'esri.layers.FeatureLayer') { // Feature Layer
                        whereByLayerDef = layer.getDefinitionExpression();

                        url = layer.url;
                    } else if (layer.declaredClass === 'esri.layers.ArcGISDynamicMapServiceLayer') { // Dynamic Layer
                        whereByLayerDef = layer.layerDefinitions && layer.layerDefinitions[qp.sublayerID];

                        if (qp.sublayerID !== null) {
                            url = layer.url + '/' + qp.sublayerID;
                        } else if (layer.visibleLayers && layer.visibleLayers.length === 1) {
                            url = layer.url + '/' + layer.visibleLayers[0];
                        }
                    }

                    if (whereByLayerDef && qp.includeLayerDefinitions) {
                        if (qp.where) {
                            qp.where = '(' + whereByLayerDef + ') AND (' + qp.where + ')';
                        } else {
                            qp.where = whereByLayerDef;
                        }
                    }
                }
            }
            return url;
        }
    });
});
<|endoftext|>


<commit_before>//-------------------------------------------
// kafe.storage
//-------------------------------------------
kafe.bonify({name:'storage', version:'1.1', obj:(function(K,undefined){
	var $ = K.jQuery;

	// test storage availability
	var
		_isLocalStorage = (function() {
			try {
				return !!localStorage.getItem;
			} catch(e) {
				return false;
			}
		})(),

		_isSessionStorage = (function() {
			try {
				return !!sessionStorage.getItem;
			} catch(e) {
				return false;
			}
		})(),

		LOCAL   = 1,
		SESSION = 2
	;

	// _isAvailable (type)
	// if storage type is available
	//-------------------------------------------
	function _isAvailable() {
		return (arguments[0] == LOCAL) ? _isLocalStorage : _isSessionStorage;
	}

	// _getStorageObj (type)
	// get storage obj
	//-------------------------------------------
	function _getStorageObj() {
		return (arguments[0] == LOCAL) ? localStorage : sessionStorage;
	}

	// _toObject(string)
	// same as kafe.string.toObject()
	//-------------------------------------------
	function _toObject(s) {

		function cast(o) {
			for (var i in o) {
				// object
				if (typeof(o[i]) == 'object') {
					o[i] = cast(o[i]);

				// date
				} else if (/^\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(o[i])) {
					o[i] = new Date(o[i]);
				}
			}
			return o;
		}

		K.required('kafe.jQuery.toJSON');
		return cast($.evalJSON(s));
	}

	// _get (type, key)
	// get data from storage
	//-------------------------------------------
	function _get(type, key) {
		if (_isAvailable(type)) {
			var data = _toObject(_getStorageObj(type).getItem(key));

			if (!!data) {

				if (!!data.expires && data.expires < new Date()) {
					_remove(type,key);

				} else if (!!data.cookie) {

					K.required('kafe.jQuery.cookie');
					if (data.cookie != $.cookie(key)) {
						_remove(type,key);

					} else {
						return data.data;
					}
				}
			}
		}
		return undefined;
	}

	// _set (type,key,value,[expires])
	// set data in storage
	//-------------------------------------------
	function _set(type,key,value,options) {
		K.required('kafe.jQuery.toJSON');

		if (_isAvailable(type)) {
			options = options || {};
			var data = {
				//modified: new Date(),
				data: value
			};

			if (!!options.expires) {
				if (options.expires == 'cookie') {
					K.required('kafe.jQuery.cookie');
					data.cookie = $.cookie(key);
				} else {
					data.expires = new Date( new Date().getTime()+(options.expires * 1000) );
				}
			}

			_getStorageObj(type).setItem(key, $.toJSON(data));
		}
	}

	// _remove (type,key)
	// remove data from storage
	//-------------------------------------------
	function _remove(type,key) {
		if (_isAvailable(type)) {
			_getStorageObj(type).removeItem(key);
		}
	}

	// _getNamespaceKeys (type,name)
	// get namespace keys from storage
	//-------------------------------------------
	function _getNamespaceKeys(type,name) {
		if (_isAvailable(type)) {
			var data = [];

			var root = _get(type, name);
			if (root != undefined) {
				data.push(name);
			}

			var s = _getStorageObj(type);
			var r = new RegExp('^'+name+':');
			for (var i in s) {
				if (r.test(i)) {
					if (_get(type,i) != undefined) {
						data.push(i);
					}
				}
			}

			return data;
		}
		return undefined;
	}

	// _getNamespaceItems (type,name)
	// get namespace data from storage
	//-------------------------------------------
	function _getNamespaceItems(type,name) {
		if (_isAvailable(type)) {
			var data = {};

			var root = _get(type, name);
			if (root != undefined) {
				data[name] = root;
			}

			var s = _getStorageObj(type);
			var r = new RegExp('^'+name+':');
			for (var i in s) {
				if (r.test(i)) {
					var d = _get(type,i);
					if (d != undefined) {
						data[i] = d;
					}
				}
			}

			return data;
		}
		return undefined;
	}

	// _removeNamespace (type, name)
	// remove namespace data from storage
	//-------------------------------------------
	function _removeNamespace(type,name) {
		if (_isAvailable(type)) {

			_remove(type,name);

			var s = _getStorageObj(type);
			var r = new RegExp('^'+name+':');
			for (var i in s) {
				if (r.test(i)) {
					_remove(type,i);
				}
			}
		}
	}

	// _getAllKeys (type)
	// get all keys from storage
	//-------------------------------------------
	function _getAllKeys(type) {
		if (_isAvailable(type)) {
			var data = [];

			var s = _getStorageObj(type);
			for (var i in s) {
				if (_get(type,i) != undefined) {
					data.push(i);
				}
			}

			return data;
		}
		return undefined;
	}

	// _getAllItems (type)
	// get all data from storage
	//-------------------------------------------
	function _getAllItems(type) {
		if (_isAvailable(type)) {
			var data = {};

			var s = _getStorageObj(type);
			for (var i in s) {
				var d = _get(type,i);
				if (d != undefined) {
					data[i] = d;
				}
			}

			return data;
		}
		return undefined;
	}

	// _removeAll (type)
	// remove all data from storage
	//-------------------------------------------
	function _removeAll(type) {
		if (_isAvailable(type)) {
			_getStorageObj(type).clear();
		}
	}

	//-------------------------------------------
	// PUBLIC
	//-------------------------------------------
	var storage = {};

	// getPersistentItem (key)
	// get data from local storage
	//-------------------------------------------
	storage.getPersistentItem = function(key) {
		return _get(LOCAL,key);
	};

	// getSessionItem (key)
	// get data from session storage
	//-------------------------------------------
	storage.getSessionItem = function(key) {
		return _get(SESSION,key);
	};

	// setPersistentItem (key,value,[expires])
	// set data in local storage
	//-------------------------------------------
	storage.setPersistentItem = function(key,value,options) {
		_set(LOCAL,key,value,options);
	};

	// setSessionItem (key,value,[expires])
	// set data in session storage
	//-------------------------------------------
	storage.setSessionItem = function(key,value,options) {
		_set(SESSION,key,value,options);
	};

	// removePersistentItem (key)
	// remove data from local storage
	//-------------------------------------------
	storage.removePersistentItem = function(key) {
		_remove(LOCAL,key);
	};

	// removeSessionItem (key)
	// remove data from session storage
	//-------------------------------------------
	storage.removeSessionItem = function(key) {
		_remove(SESSION,key);
	};

	// getPersistentNamespaceKeys (name)
	// get namespace keys from local storage
	//-------------------------------------------
	storage.getPersistentNamespaceKeys = function(name) {
		return _getNamespaceKeys(LOCAL,name);
	};

	// getSessionNamespaceKeys (name)
	// get namespace keys from session storage
	//-------------------------------------------
	storage.getSessionNamespaceKeys = function(name) {
		return _getNamespaceKeys(SESSION,name);
	};

	// getPersistentNamespaceItems (name)
	// get namespace data from local storage
	//-------------------------------------------
	storage.getPersistentNamespaceItems = function(name) {
		return _getNamespaceItems(LOCAL,name);
	};

	// getSessionNamespaceItems (name)
	// get namespace data from session storage
	//-------------------------------------------
	storage.getSessionNamespaceItems = function(name) {
		return _getNamespaceItems(SESSION,name);
	};

	// removePersistentNamespace (name)
	// remove namespace data from local storage
	//-------------------------------------------
	storage.removePersistentNamespace = function(name) {
		_removeNamespace(LOCAL,name);
	};

	// removeSessionNamespace (key)
	// remove namespace data from session storage
	//-------------------------------------------
	storage.removeSessionNamespace = function(name) {
		_removeNamespace(SESSION,name);
	};

	// getAllPersistentKeys ()
	// get all keys from local storage
	//-------------------------------------------
	storage.getAllPersistentKeys = function() {
		return _getAllKeys(LOCAL);
	};

	// getAllSessionKeys ()
	// get all keys from session storage
	//-------------------------------------------
	storage.getAllSessionKeys = function() {
		return _getAllKeys(SESSION);
	};

	// getAllPersistentItems ()
	// get all data from local storage
	//-------------------------------------------
	storage.getAllPersistentItems = function() {
		return _getAllItems(LOCAL);
	};

	// getAllSessionItems ()
	// get all data from session storage
	//-------------------------------------------
	storage.getAllSessionItems = function() {
		return _getAllItems(SESSION);
	};

	// removeAllPersistent ()
	// remove all data from local storage
	//-------------------------------------------
	storage.removeAllPersistent = function() {
		_removeAll(LOCAL);
	};

	// removeAllSession ()
	// remove all data from session storage
	//-------------------------------------------
	storage.removeAllSession = function() {
		_removeAll(SESSION);
	};

	// getJSON (url [,data] ,callback)
	// call and cache a getJSON() call
	//-------------------------------------------
	storage.getJSON = function() {
		if (_isAvailable(SESSION)) {
			var
				url      = arguments[0],
				options  = (typeof(arguments[1]) != 'function') ? arguments[1] : {expires:600},
				callback = (typeof(arguments[1]) != 'function') ? arguments[2] : arguments[1],
				key      = 'kafe-storage-getJSON_'+url.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
				cache    = storage.getSessionItem(key)
			;

			if (cache != undefined) {
				callback(cache);
			} else {
				$.getJSON(url, function(data) {
					storage.setSessionItem(key, data, options);
					callback(data);
				});
			}
		}
	};

	return storage;

})(kafe)});
<commit_msg>Correction bug sous Firefox<commit_after>//-------------------------------------------
// kafe.storage
//-------------------------------------------
kafe.bonify({name:'storage', version:'1.1', obj:(function(K,undefined){
	var $ = K.jQuery;

	// test storage availability
	var
		_isLocalStorage = (function() {
			try {
				return !!localStorage.getItem;
			} catch(e) {
				return false;
			}
		})(),

		_isSessionStorage = (function() {
			try {
				return !!sessionStorage.getItem;
			} catch(e) {
				return false;
			}
		})(),

		LOCAL   = 1,
		SESSION = 2
	;

	// _isAvailable (type)
	// if storage type is available
	//-------------------------------------------
	function _isAvailable() {
		return (arguments[0] == LOCAL) ? _isLocalStorage : _isSessionStorage;
	}

	// _getStorageObj (type)
	// get storage obj
	//-------------------------------------------
	function _getStorageObj() {
		return (arguments[0] == LOCAL) ? localStorage : sessionStorage;
	}

	// _toObject(string)
	// same as kafe.string.toObject()
	//-------------------------------------------
	function _toObject(s) {

		function cast(o) {
			for (var i in o) {
				// object
				if (typeof(o[i]) == 'object') {
					o[i] = cast(o[i]);

				// date
				} else if (/^\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(o[i])) {
					o[i] = new Date(o[i]);
				}
			}
			return o;
		}

		K.required('kafe.jQuery.toJSON');
		return cast($.evalJSON(s));
	}

	// _get (type, key)
	// get data from storage
	//-------------------------------------------
	function _get(type, key) {
		if (_isAvailable(type)) {
			var
				sData = _getStorageObj(type).getItem(key),
				data = (sData) ? K.string.toObject(sData) : undefined
			;
			if (!!data) {

				if (!!data.expires && data.expires < new Date()) {
					_remove(type,key);

				} else if (!!data.cookie) {

					K.required('kafe.jQuery.cookie');
					if (data.cookie != $.cookie(key)) {
						_remove(type,key);

					} else {
						return data.data;
					}
				}
			}
		}
		return undefined;
	}

	// _set (type,key,value,[expires])
	// set data in storage
	//-------------------------------------------
	function _set(type,key,value,options) {
		K.required('kafe.jQuery.toJSON');

		if (_isAvailable(type)) {
			options = options || {};
			var data = {
				//modified: new Date(),
				data: value
			};

			if (!!options.expires) {
				if (options.expires == 'cookie') {
					K.required('kafe.jQuery.cookie');
					data.cookie = $.cookie(key);
				} else {
					data.expires = new Date( new Date().getTime()+(options.expires * 1000) );
				}
			}

			_getStorageObj(type).setItem(key, $.toJSON(data));
		}
	}

	// _remove (type,key)
	// remove data from storage
	//-------------------------------------------
	function _remove(type,key) {
		if (_isAvailable(type)) {
			_getStorageObj(type).removeItem(key);
		}
	}

	// _getNamespaceKeys (type,name)
	// get namespace keys from storage
	//-------------------------------------------
	function _getNamespaceKeys(type,name) {
		if (_isAvailable(type)) {
			var data = [];

			var root = _get(type, name);
			if (root != undefined) {
				data.push(name);
			}

			var s = _getStorageObj(type);
			var r = new RegExp('^'+name+':');
			for (var i in s) {
				if (r.test(i)) {
					if (_get(type,i) != undefined) {
						data.push(i);
					}
				}
			}

			return data;
		}
		return undefined;
	}

	// _getNamespaceItems (type,name)
	// get namespace data from storage
	//-------------------------------------------
	function _getNamespaceItems(type,name) {
		if (_isAvailable(type)) {
			var data = {};

			var root = _get(type, name);
			if (root != undefined) {
				data[name] = root;
			}

			var s = _getStorageObj(type);
			var r = new RegExp('^'+name+':');
			for (var i in s) {
				if (r.test(i)) {
					var d = _get(type,i);
					if (d != undefined) {
						data[i] = d;
					}
				}
			}

			return data;
		}
		return undefined;
	}

	// _removeNamespace (type, name)
	// remove namespace data from storage
	//-------------------------------------------
	function _removeNamespace(type,name) {
		if (_isAvailable(type)) {

			_remove(type,name);

			var s = _getStorageObj(type);
			var r = new RegExp('^'+name+':');
			for (var i in s) {
				if (r.test(i)) {
					_remove(type,i);
				}
			}
		}
	}

	// _getAllKeys (type)
	// get all keys from storage
	//-------------------------------------------
	function _getAllKeys(type) {
		if (_isAvailable(type)) {
			var data = [];

			var s = _getStorageObj(type);
			for (var i in s) {
				if (_get(type,i) != undefined) {
					data.push(i);
				}
			}

			return data;
		}
		return undefined;
	}

	// _getAllItems (type)
	// get all data from storage
	//-------------------------------------------
	function _getAllItems(type) {
		if (_isAvailable(type)) {
			var data = {};

			var s = _getStorageObj(type);
			for (var i in s) {
				var d = _get(type,i);
				if (d != undefined) {
					data[i] = d;
				}
			}

			return data;
		}
		return undefined;
	}

	// _removeAll (type)
	// remove all data from storage
	//-------------------------------------------
	function _removeAll(type) {
		if (_isAvailable(type)) {
			_getStorageObj(type).clear();
		}
	}

	//-------------------------------------------
	// PUBLIC
	//-------------------------------------------
	var storage = {};

	// getPersistentItem (key)
	// get data from local storage
	//-------------------------------------------
	storage.getPersistentItem = function(key) {
		return _get(LOCAL,key);
	};

	// getSessionItem (key)
	// get data from session storage
	//-------------------------------------------
	storage.getSessionItem = function(key) {
		return _get(SESSION,key);
	};

	// setPersistentItem (key,value,[expires])
	// set data in local storage
	//-------------------------------------------
	storage.setPersistentItem = function(key,value,options) {
		_set(LOCAL,key,value,options);
	};

	// setSessionItem (key,value,[expires])
	// set data in session storage
	//-------------------------------------------
	storage.setSessionItem = function(key,value,options) {
		_set(SESSION,key,value,options);
	};

	// removePersistentItem (key)
	// remove data from local storage
	//-------------------------------------------
	storage.removePersistentItem = function(key) {
		_remove(LOCAL,key);
	};

	// removeSessionItem (key)
	// remove data from session storage
	//-------------------------------------------
	storage.removeSessionItem = function(key) {
		_remove(SESSION,key);
	};

	// getPersistentNamespaceKeys (name)
	// get namespace keys from local storage
	//-------------------------------------------
	storage.getPersistentNamespaceKeys = function(name) {
		return _getNamespaceKeys(LOCAL,name);
	};

	// getSessionNamespaceKeys (name)
	// get namespace keys from session storage
	//-------------------------------------------
	storage.getSessionNamespaceKeys = function(name) {
		return _getNamespaceKeys(SESSION,name);
	};

	// getPersistentNamespaceItems (name)
	// get namespace data from local storage
	//-------------------------------------------
	storage.getPersistentNamespaceItems = function(name) {
		return _getNamespaceItems(LOCAL,name);
	};

	// getSessionNamespaceItems (name)
	// get namespace data from session storage
	//-------------------------------------------
	storage.getSessionNamespaceItems = function(name) {
		return _getNamespaceItems(SESSION,name);
	};

	// removePersistentNamespace (name)
	// remove namespace data from local storage
	//-------------------------------------------
	storage.removePersistentNamespace = function(name) {
		_removeNamespace(LOCAL,name);
	};

	// removeSessionNamespace (key)
	// remove namespace data from session storage
	//-------------------------------------------
	storage.removeSessionNamespace = function(name) {
		_removeNamespace(SESSION,name);
	};

	// getAllPersistentKeys ()
	// get all keys from local storage
	//-------------------------------------------
	storage.getAllPersistentKeys = function() {
		return _getAllKeys(LOCAL);
	};

	// getAllSessionKeys ()
	// get all keys from session storage
	//-------------------------------------------
	storage.getAllSessionKeys = function() {
		return _getAllKeys(SESSION);
	};

	// getAllPersistentItems ()
	// get all data from local storage
	//-------------------------------------------
	storage.getAllPersistentItems = function() {
		return _getAllItems(LOCAL);
	};

	// getAllSessionItems ()
	// get all data from session storage
	//-------------------------------------------
	storage.getAllSessionItems = function() {
		return _getAllItems(SESSION);
	};

	// removeAllPersistent ()
	// remove all data from local storage
	//-------------------------------------------
	storage.removeAllPersistent = function() {
		_removeAll(LOCAL);
	};

	// removeAllSession ()
	// remove all data from session storage
	//-------------------------------------------
	storage.removeAllSession = function() {
		_removeAll(SESSION);
	};

	// getJSON (url [,data] ,callback)
	// call and cache a getJSON() call
	//-------------------------------------------
	storage.getJSON = function() {
		if (_isAvailable(SESSION)) {
			var
				url      = arguments[0],
				options  = (typeof(arguments[1]) != 'function') ? arguments[1] : {expires:600},
				callback = (typeof(arguments[1]) != 'function') ? arguments[2] : arguments[1],
				key      = 'kafe-storage-getJSON_'+url.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
				cache    = storage.getSessionItem(key)
			;

			if (cache != undefined) {
				callback(cache);
			} else {
				$.getJSON(url, function(data) {
					storage.setSessionItem(key, data, options);
					callback(data);
				});
			}
		}
	};

	return storage;

})(kafe)});
<|endoftext|>


<commit_before>// import { Mongo } from 'meteor/mongo';
// const Posts = new Mongo.Collection('posts');
// new Meteor.Pagination(Posts);
// export { Posts };
//
// // if (Meteor.isServer) {
// //   // This code only runs on the server
// //   Meteor.publish('posts', function postsPublication() {
// //     return Posts.find();
// //   });
// // }
// if (Meteor.isServer) {
//   // This code only runs on the server
// new Meteor.Pagination(Posts);
// }
// index.js file here.....
import { Mongo } from 'meteor/mongo';
const Posts = new Mongo.Collection('posts');
export { Posts };

if (Meteor.isServer) {
  // This code only runs on the server
new Meteor.Pagination(Posts);
}
<commit_msg>Corrected indentations<commit_after>import { Mongo } from 'meteor/mongo';
const Posts = new Mongo.Collection('posts');
export { Posts };

// This code only runs on the server
if (Meteor.isServer) {
  // Use pagination when posts are requested
  new Meteor.Pagination(Posts);
}
<|endoftext|>


<commit_before>import {dispatch, matcher} from 'common/functional';

import gameKeyboardController from 'game/keyboard-controller';
import Ball from 'game/entities/ball';
import Vaus from 'game/entities/vaus';
import PowerUp from 'game/entities/power-up';
import Level  from 'game/level';
import CreateWalls from 'game/entities/wall';
import GameModel from 'game/model';

import Coordinates from 'graphics/coordinates';
import Scene from 'graphics/scene';

import {bounce, overlap} from 'physics/collisions';

import Vector from 'maths/vector';

import soundController  from 'sound/arkanoid/sound-controller';

import cond from 'lodash.cond';
import is_nil from 'lodash.isnil';
import random from 'lodash.random';

export default function GameController({model, view, keyboard}) {
	const scene = view.scene();
	const screen = view.screen();
	const gameScene = Scene(Coordinates({
		width: scene.width() - 2,
		height: scene.height() - 1
	}, {x: 1, y: 1}));
	const gameZone = gameScene.localRect();
	const brickScene = Scene(Coordinates(gameZone.size), Vector.Null);
	const level = Level();
	const ball = Ball(Vector.Null);
	const vaus = Vaus({x: 1, y: gameScene.height() - 2});
	const pills = new Set();

	//////////////////////////////////////////////////////////////////////////
	// Collision helpers

	function ball_collides_with_bricks(ball_box, speed) {
		for (let brick of level.neighborhood(ball.position())) {
			const brick_box = brick.rect();
			const v = bounce(ball_box, speed, brick_box, .001);
			if (!is_nil(v)) {
				ball.emit('hit', 'brick');
				brick.hit();
				return v.add({
					x: random(-1, 1, true)/1000,
					y: random(-1, 1, true)/1000
				}).toUnit().mul(.2);
			}
		}
	}

	function ball_collides_with_vaus(ball_box, speed) {
		const v = bounce(ball_box, speed, vaus.rect(), 1/16);
		if (!is_nil(v)) {
			ball.emit('hit', 'vaus');
			return v;
		}
	}

	function ball_collides_with_walls(ball_box, speed) {
		if (ball_box.leftX <= gameZone.leftX) {
			ball.emit('hit', 'wall');
			// collide with left wall
			return Vector({x: -speed.x, y: speed.y});
		} else if (ball_box.rightX >= gameZone.rightX) {
			ball.emit('hit', 'wall');
			// collide with right wall
			return Vector({x: -speed.x, y: speed.y});
		} else if (ball_box.topY <= gameZone.topY) {
			// collide with roof
			ball.emit('hit', 'wall');
			return Vector({x: speed.x, y: -speed.y});
		}
	}

	function ball_goes_out(ball_box, speed) {
		if (ball_box.bottomY >= gameZone.bottomY) {
			if(model.cheatMode()) {
				ball.emit('hit', 'wall');
				return Vector({x: speed.x, y: -speed.y});
			} else {
				ball.emit('hit', 'ground');
				return Vector.Null;
			}
		}
	}

	const ball_collides = dispatch(
		ball_collides_with_bricks,
		ball_collides_with_vaus,
		ball_collides_with_walls,
		ball_goes_out
	);

	function pills_collides() {
		for (let pill of pills) {
			const pill_box = pill.rect();
			const o = overlap(pill_box, vaus.rect(), pill.velocity().y);
			if (o !== overlap.NONE || pill_box.topY >= gameZone.bottomY) {
				pills.delete(pill);
				gameScene.remove(pill);
				if (o !== overlap.NONE) {
					vaus.emit('powerUp', pill.type());
				}
			}
		}
	}

	//////////////////////////////////////////////////////////////////////////
	// Position helpers

	function reset_ball_position() {
		const vaus_box = vaus.rect();
		ball.reset(vaus_box.center.sub({
			x: ball.size().width/2,
			y: ball.size().height + vaus_box.height/2
		}));
	}

	function reset_vaus_position() {
		vaus.reset({x: 1, y: gameZone.height - 2});
	}

	function update_ball() {
		if (!ball.velocity().isNull()) {
			const ball_box = ball.rect().translate(ball.velocity());
			const ball_speed = ball_collides(ball_box, ball.velocity());
			if (!is_nil(ball_speed)) {
				ball.setVelocity(ball_speed);
			}
		} else {
			reset_ball_position(vaus, ball);
		}
		ball.update();
	}

	function update_vaus() {
		const {leftX: vaus_left_x, rightX: vaus_right_x} = vaus.rect();
		const {leftX: zone_left_x, rightX: zone_right_x} = gameScene.localRect();

		if (!vaus.velocity().isNull() && vaus_left_x <= zone_left_x) {
			vaus.move(Vector.Null);
			vaus.setPosition(vaus.position().add({x: zone_left_x - vaus_left_x, y: 0}));
		}

		if (!vaus.velocity().isNull() && vaus_right_x >= zone_right_x) {
			vaus.move(Vector.Null);
			vaus.setPosition(vaus.position().add({x: zone_right_x - vaus_right_x, y: 0}));
		}

		vaus.update();
	}

	function update() {
		if (model.isRunning()) {
			pills_collides();
			for (let pill of pills) {
				pill.update();
			}
			update_ball();
			update_vaus();
		}
	}

	//////////////////////////////////////////////////////////////////////////
	// Game state helpers

	function loop() {
		update();
		screen.render();
		requestAnimationFrame(loop);
	}

	ball
		.on('hit', cond([
			[matcher('brick'), soundController.ballCollidesWithBricks],
			[matcher('vaus'), soundController.ballCollidesWithVaus],
			[matcher('ground'), () => {
				soundController.ballGoesOut();
				if (model.lifeCount() > 0) {
					model.setState(GameModel.state.Ready);
				} else {
					model.setState(GameModel.state.GameOver);
				}
			}]
		]));
	vaus
		.on('powerUp', cond([
			[matcher(PowerUp.ExtraLife), () => model.gainLife()],
			[matcher(PowerUp.Expand), () => vaus.setMode(Vaus.Mode.Large)],
			[matcher(PowerUp.Laser), () => vaus.setMode(Vaus.Mode.Armed)]
		]))
	keyboard
		.on('direction-changed', direction => {
			vaus.move(direction)
		})
		.on('pause', () => {
			model.setState(GameModel.state.Paused);
		})
		.on('fire', () => {
			if (ball.velocity().isNull()) {
				ball.setVelocity(Vector({x: 1, y: -1}).toUnit().mul(.2));
			}
		});
	model
		.on('reset', () => {
			level.reset();
			brickScene.reset();
			ball.hide();
			vaus.hide();
		})
		.on('changed', cond([
			[matcher('stage'), () => {
				level.reset(model.bricks());
				brickScene.reset().add(...level);
			}],
			[matcher('state', GameModel.state.Paused), () => {
				ball.hide();
				vaus.hide();
			}],
			[matcher('state', GameModel.state.Ready), () => {
				keyboard.use(null);
				ball.show();
				vaus.show();
				model.takeLife();
				reset_vaus_position();
				reset_ball_position();
			}],
			[matcher('state', GameModel.state.Running), () => {
				keyboard.use(gameKeyboardController);
				ball.show();
				vaus.show();
				if (ball.velocity().isNull()) {
					ball.setVelocity(Vector({x: 1, y: -1}).toUnit().mul(.2));
				}
			}]
		]));
	level
		.on('itemChanged', brick => {
			const points = brick.points();
			if (points > 0) {
				model.updateScore(points);
			}
		})
		.on('itemDestroyed', brick => {
			brick.hide();
		})
		.on('powerUp', power_up => {
			gameScene.add(power_up);
			pills.add(power_up);
		})
		.on('completed', () => {
			if (model.isRunning()) {
				ball.hide();
				vaus.hide();
				model.gainLife();
				model.nextStage();
				model.setState(GameModel.state.Ready);
			}
		});

	vaus.hide();
	ball.hide();
	gameScene.add(brickScene, ball, vaus);
	scene.add(...CreateWalls(scene.width() - 1, scene.height()), gameScene);

	return {
		run() {
			loop();
			return this;
		}
	};
}
<commit_msg>Remove all pending pills on Ready state<commit_after>import {dispatch, matcher} from 'common/functional';

import gameKeyboardController from 'game/keyboard-controller';
import Ball from 'game/entities/ball';
import Vaus from 'game/entities/vaus';
import PowerUp from 'game/entities/power-up';
import Level  from 'game/level';
import CreateWalls from 'game/entities/wall';
import GameModel from 'game/model';

import Coordinates from 'graphics/coordinates';
import Scene from 'graphics/scene';

import {bounce, overlap} from 'physics/collisions';

import Vector from 'maths/vector';

import soundController  from 'sound/arkanoid/sound-controller';

import cond from 'lodash.cond';
import is_nil from 'lodash.isnil';
import random from 'lodash.random';

export default function GameController({model, view, keyboard}) {
	const scene = view.scene();
	const screen = view.screen();
	const gameScene = Scene(Coordinates({
		width: scene.width() - 2,
		height: scene.height() - 1
	}, {x: 1, y: 1}));
	const gameZone = gameScene.localRect();
	const brickScene = Scene(Coordinates(gameZone.size), Vector.Null);
	const level = Level();
	const ball = Ball(Vector.Null);
	const vaus = Vaus({x: 1, y: gameScene.height() - 2});
	const pills = new Set();

	//////////////////////////////////////////////////////////////////////////
	// Collision helpers

	function ball_collides_with_bricks(ball_box, speed) {
		for (let brick of level.neighborhood(ball.position())) {
			const brick_box = brick.rect();
			const v = bounce(ball_box, speed, brick_box, .001);
			if (!is_nil(v)) {
				ball.emit('hit', 'brick');
				brick.hit();
				return v.add({
					x: random(-1, 1, true)/1000,
					y: random(-1, 1, true)/1000
				}).toUnit().mul(.2);
			}
		}
	}

	function ball_collides_with_vaus(ball_box, speed) {
		const v = bounce(ball_box, speed, vaus.rect(), 1/16);
		if (!is_nil(v)) {
			ball.emit('hit', 'vaus');
			return v;
		}
	}

	function ball_collides_with_walls(ball_box, speed) {
		if (ball_box.leftX <= gameZone.leftX) {
			ball.emit('hit', 'wall');
			// collide with left wall
			return Vector({x: -speed.x, y: speed.y});
		} else if (ball_box.rightX >= gameZone.rightX) {
			ball.emit('hit', 'wall');
			// collide with right wall
			return Vector({x: -speed.x, y: speed.y});
		} else if (ball_box.topY <= gameZone.topY) {
			// collide with roof
			ball.emit('hit', 'wall');
			return Vector({x: speed.x, y: -speed.y});
		}
	}

	function ball_goes_out(ball_box, speed) {
		if (ball_box.bottomY >= gameZone.bottomY) {
			if(model.cheatMode()) {
				ball.emit('hit', 'wall');
				return Vector({x: speed.x, y: -speed.y});
			} else {
				ball.emit('hit', 'ground');
				return Vector.Null;
			}
		}
	}

	const ball_collides = dispatch(
		ball_collides_with_bricks,
		ball_collides_with_vaus,
		ball_collides_with_walls,
		ball_goes_out
	);

	function pills_collides() {
		for (let pill of pills) {
			const pill_box = pill.rect();
			const o = overlap(pill_box, vaus.rect(), pill.velocity().y);
			if (o !== overlap.NONE || pill_box.topY >= gameZone.bottomY) {
				pills.delete(pill);
				gameScene.remove(pill);
				if (o !== overlap.NONE) {
					vaus.emit('powerUp', pill.type());
				}
			}
		}
	}

	//////////////////////////////////////////////////////////////////////////
	// Position helpers

	function reset_ball_position() {
		const vaus_box = vaus.rect();
		ball.reset(vaus_box.center.sub({
			x: ball.size().width/2,
			y: ball.size().height + vaus_box.height/2
		}));
	}

	function reset_vaus_position() {
		vaus.reset({x: 1, y: gameZone.height - 2});
	}

	function update_ball() {
		if (!ball.velocity().isNull()) {
			const ball_box = ball.rect().translate(ball.velocity());
			const ball_speed = ball_collides(ball_box, ball.velocity());
			if (!is_nil(ball_speed)) {
				ball.setVelocity(ball_speed);
			}
		} else {
			reset_ball_position(vaus, ball);
		}
		ball.update();
	}

	function update_vaus() {
		const {leftX: vaus_left_x, rightX: vaus_right_x} = vaus.rect();
		const {leftX: zone_left_x, rightX: zone_right_x} = gameScene.localRect();

		if (!vaus.velocity().isNull() && vaus_left_x <= zone_left_x) {
			vaus.move(Vector.Null);
			vaus.setPosition(vaus.position().add({x: zone_left_x - vaus_left_x, y: 0}));
		}

		if (!vaus.velocity().isNull() && vaus_right_x >= zone_right_x) {
			vaus.move(Vector.Null);
			vaus.setPosition(vaus.position().add({x: zone_right_x - vaus_right_x, y: 0}));
		}

		vaus.update();
	}

	function update() {
		if (model.isRunning()) {
			pills_collides();
			for (let pill of pills) {
				pill.update();
			}
			update_ball();
			update_vaus();
		}
	}

	//////////////////////////////////////////////////////////////////////////
	// Game state helpers

	function loop() {
		update();
		screen.render();
		requestAnimationFrame(loop);
	}

	ball
		.on('hit', cond([
			[matcher('brick'), soundController.ballCollidesWithBricks],
			[matcher('vaus'), soundController.ballCollidesWithVaus],
			[matcher('ground'), () => {
				soundController.ballGoesOut();
				if (model.lifeCount() > 0) {
					model.setState(GameModel.state.Ready);
				} else {
					model.setState(GameModel.state.GameOver);
				}
			}]
		]));
	vaus
		.on('powerUp', cond([
			[matcher(PowerUp.ExtraLife), () => model.gainLife()],
			[matcher(PowerUp.Expand), () => vaus.setMode(Vaus.Mode.Large)],
			[matcher(PowerUp.Laser), () => vaus.setMode(Vaus.Mode.Armed)]
		]))
	keyboard
		.on('direction-changed', direction => {
			vaus.move(direction)
		})
		.on('pause', () => {
			model.setState(GameModel.state.Paused);
		})
		.on('fire', () => {
			if (ball.velocity().isNull()) {
				ball.setVelocity(Vector({x: 1, y: -1}).toUnit().mul(.2));
			}
		});
	model
		.on('reset', () => {
			level.reset();
			brickScene.reset();
			ball.hide();
			vaus.hide();
		})
		.on('changed', cond([
			[matcher('stage'), () => {
				level.reset(model.bricks());
				brickScene.reset().add(...level);
			}],
			[matcher('state', GameModel.state.Paused), () => {
				ball.hide();
				vaus.hide();
			}],
			[matcher('state', GameModel.state.Ready), () => {
				keyboard.use(null);
				for (let pill of pills) {
					pills.delete(pill);
					gameScene.remove(pill);
				}
				ball.show();
				vaus.show();
				model.takeLife();
				reset_vaus_position();
				reset_ball_position();
			}],
			[matcher('state', GameModel.state.Running), () => {
				keyboard.use(gameKeyboardController);
				ball.show();
				vaus.show();
				if (ball.velocity().isNull()) {
					ball.setVelocity(Vector({x: 1, y: -1}).toUnit().mul(.2));
				}
			}]
		]));
	level
		.on('itemChanged', brick => {
			const points = brick.points();
			if (points > 0) {
				model.updateScore(points);
			}
		})
		.on('itemDestroyed', brick => {
			brick.hide();
		})
		.on('powerUp', power_up => {
			if (model.isRunning()) {
				gameScene.add(power_up);
				pills.add(power_up);
			}
		})
		.on('completed', () => {
			if (model.isRunning()) {
				ball.hide();
				vaus.hide();
				model.gainLife();
				model.nextStage();
				model.setState(GameModel.state.Ready);
			}
		});

	vaus.hide();
	ball.hide();
	gameScene.add(brickScene, ball, vaus);
	scene.add(...CreateWalls(scene.width() - 1, scene.height()), gameScene);

	return {
		run() {
			loop();
			return this;
		}
	};
}
<|endoftext|>


<commit_before>// get default profile

/**
 * @api {get} /accounts/:account_id/configuration Get Default Profile
 * @apiName Get Default Profile
 * @apiGroup Account Configuration
 * @apiVersion 1.0.0
 *
 * @apiDescription Get the default ingest profile for the account.
 *
 * @apiHeader {String} Content-Type Content-Type: application/json
 * @apiHeader {String} Authorization Authorization: Bearer access_token (see [Getting Access Tokens](https://support.brightcove.com/getting-access-tokens))
 *
 * @apiParam {String} account_id Video Cloud account ID
 *
 * @apiParamExample {json} Get Default Profile Example:
 *     https://ingestion.api.brightcove.com/v1/accounts/57838016001/configuration
 *
 * @apiSuccess (200) {Number} account_id Video Cloud account id
 * @apiSuccess (200) {String} id configuration id
 * @apiSuccess (200) {String} default_profile_id profile name for video-on-demand
 * @apiSuccess (200) {String} default_live_profile_id default profile name for live streams
 * @apiSuccess (200) {Number} date_created when the profile was created (epoch time in milliseconds)
 * @apiSuccess (200) {Number} date_last_modified when the profile was last modified (epoch time in milliseconds)
 * @apiSuccess (200) {Number} max_profile_count maximum number of custom profiles for the account
 * @apiSuccess (200) {Number} max_rendition_count maximum number of renditions per profile
 * @apiSuccess (200) {Number} version system-managed version number
 *
 * @apiSuccessExample {object} Success Response:
 *    HTTP/1.1 200 OK
 *    {
 *        "account_id": 57838016001,
 *        "date_created": 1442409154636,
 *        "date_last_modified": 1442409154636,
 *        "default_live_profile_id": "Live - Standard",
 *        "default_profile_id": "screencast-1280",
 *        "id": "55525f84e4b08e946aa03281",
 *        "max_profile_count": 10,
 *        "max_rendition_count": 20,
 *        "version": 1442409154636
 *    }
 *
 * @apiError (Error 4xx) {array} NOT_AUTHORIZED 401: Credentials are required to access this resource
 * @apiError (Error 4xx) {html} NOT_FOUND 404: The api couldn't find the resource you requested
 *
 * @apiErrorExample {array} 409 Error Response
 *    HTTP/1.1 404 NOT_FOUND
 *    [
 *        {
 *            "error_code": "NOT_AUTHORIZED",
 *            "message": "Credentials are required to access this resource."
 *        }
 *    ]
 *
 * @apiErrorExample {string} 404 Error Response
 *    HTTP/1.1 404 NOT_FOUND
 *      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
*    <title>Error 404 NOT_FOUND</title>
*
HTTP ERROR 404

Problem accessing /v1/accounts/57838016001/configurtion. Reason:
 NOT_FOUND

*

 *
 */

// set default profile

/**
 * @api {post} /accounts/:account_id/configuration Set Default Profile
 * @apiName Set Default Profile
 * @apiGroup Account Configuration
 * @apiVersion 1.0.0
 *
 * @apiDescription Sets an ingest profile as the default for the account.
 *
 * @apiHeader {String} Content-Type Content-Type: application/json
 * @apiHeader {String} Authorization Authorization: Bearer access_token (see [Getting Access Tokens](https://support.brightcove.com/getting-access-tokens))
 *
 * @apiParam {String} account_id Video Cloud account ID
 * @apiParam (Request Body Fields) {Number} account_id Video Cloud account ID
 * @apiParam (Request Body Fields) {String} default_profile_id The id or name of the profile you want to set as the default
 * @apiParam (Request Body Fields) {String} [default_live_profile_id] The id or name of the live profile you want to set as the default
 *
 * @apiParamExample {json} Set Default Profile Example:
 *     {
 *         "account_id": 57838016001,
 *         "default_profile_id": "high-resolution"
 *     }
 *
 * @apiSuccess (200) {Number} account_id Video Cloud account id
 * @apiSuccess (200) {String} id configuration id
 * @apiSuccess (200) {String} default_profile_id profile name for video-on-demand
 * @apiSuccess (200) {String} default_live_profile_id default profile name for live streams
 * @apiSuccess (200) {Number} date_created when the profile was created (epoch time in milliseconds)
 * @apiSuccess (200) {Number} date_last_modified when the profile was last modified (epoch time in milliseconds)
 * @apiSuccess (200) {Number} max_profile_count maximum number of custom profiles for the account
 * @apiSuccess (200) {Number} max_rendition_count maximum number of renditions per profile
 * @apiSuccess (200) {Number} version system-managed version number
 *
 * @apiSuccessExample {json} Success Response:
 *    HTTP/1.1 200 OK
 *    {
 *        "account_id": 57838016001,
 *        "date_created": 1443727850896,
 *        "date_last_modified": 1443727850896,
 *        "default_live_profile_id": "Live - Standard",
 *        "default_profile_id": "high-resolution",
 *        "id": "55525f84e4b08e946aa03281",
 *        "max_profile_count": 10,
 *        "max_rendition_count": 20,
 *        "version": 1443727850896
 *    }
 *
 * @apiError (Error 4xx) {json} NOT_AUTHORIZED 401: Credentials are required to access this resource.
 * @apiError (Error 4xx) {html} NOT_FOUND 404: The api couldn't find the resource you requested
 * @apiError (Error 4xx) {html} BAD_REQUEST 400: The JSON was not valid
 * @apiError (Error 4xx) {json} CONFLICT 409: Account configuration already exists for 57838016001; please delete the configuration first, or update it instead.
 *
 * @apiErrorExample {json} 401 Error Response
 *    HTTP/1.1 401 NOT_AUTHORIZED
 *    [
 *        {
 *            "error_code": "NOT_AUTHORIZED",
 *            "message": "Credentials are required to access this resource."
 *        }
 *    ]
 * @apiErrorExample {html} 404 Error Response
 *    HTTP/1.1 404 NOT_FOUND
 *      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
*    <title>Error 404 NOT_FOUND</title>
*
HTTP ERROR 404

Problem accessing /v1/accounts/57838016001/configurtion. Reason:
 NOT_FOUND

*

* @apiErrorExample {html} 400 BAD_REQUEST
*     HTTP/1.1 400 BAD_REQUEST
*       <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
*     <title>Error 400 Unexpected character ('d' (code 100)): was expecting a colon to separate field name and value</title>
*
HTTP ERROR 400

Problem accessing /v1/accounts/57838016001/configuration. Reason:
 Unexpected character ('d' (code 100)): was expecting a colon to separate field name and value

*

*
* @apiErrorExample {json} 409 CONFLICT
*    HTTP/1.1 409 CONFLICT
*    [
*        {
*            "code": "CONFLICT",
*            "message": "Account configuration already exists for 57838016001; please delete the configuration first, or update it instead."
*        }
*    ]
*
 */

// update default profile

/**
 * @api {put} /accounts/:account_id/configuration Update Default Profile
 * @apiName Update Default Profile
 * @apiGroup Account Configuration
 * @apiVersion 1.0.0
 *
 * @apiDescription Updates the default ingest profile for the account.
 *
 * @apiHeader {String} Content-Type Content-Type: application/json
 * @apiHeader {String} Authorization Authorization: Bearer access_token (see [Getting Access Tokens](https://support.brightcove.com/getting-access-tokens))
 *
 * @apiParam {String} account_id Video Cloud account ID
 * @apiParam (Request Body Fields) {Number} account_id Video Cloud account ID
 * @apiParam (Request Body Fields) {String} id the configuration id (if you don't have it, make a GET request to get it)
 * @apiParam (Request Body Fields) {String} default_profile_id The id or name of the profile you want to set as the default
 * @apiParam (Request Body Fields) {String} [default_live_profile_id] The id or name of the live profile you want to set as the default
 *
 * @apiParamExample {json} Update Default Profile Example:
 *     {
 *         "account_id": 57838016001,
 *         "default_profile_id": "high-resolution"
 *     }
 *
 * @apiSuccess (200) {Number} account_id Video Cloud account id
 * @apiSuccess (200) {String} id configuration id
 * @apiSuccess (200) {String} default_profile_id profile name for video-on-demand
 * @apiSuccess (200) {String} default_live_profile_id default profile name for live streams
 * @apiSuccess (200) {Number} date_created when the profile was created (epoch time in milliseconds)
 * @apiSuccess (200) {Number} date_last_modified when the profile was last modified (epoch time in milliseconds)
 * @apiSuccess (200) {Number} max_profile_count maximum number of custom profiles for the account
 * @apiSuccess (200) {Number} max_rendition_count maximum number of renditions per profile
 * @apiSuccess (200) {Number} version system-managed version number
 *
 * @apiSuccessExample {json} Success Response:
 *    HTTP/1.1 200 OK
 *    {
 *        "account_id": 57838016001,
 *        "date_created": 1443727850896,
 *        "date_last_modified": 1443727850896,
 *        "default_live_profile_id": "Live - Standard",
 *        "default_profile_id": "high-resolution",
 *        "id": "55525f84e4b08e946aa03281",
 *        "max_profile_count": 10,
 *        "max_rendition_count": 20,
 *        "version": 1443727850896
 *    }
 *
 * @apiError (Error 4xx) {json} NOT_AUTHORIZED 401: Credentials are required to access this resource.
 * @apiError (Error 4xx) {html} NOT_FOUND 404: The api couldn't find the resource you requested
 * @apiError (Error 4xx) {html} BAD_REQUEST 400: The JSON was not valid
 * @apiError (Error 4xx) {json} CONFLICT 409: Account configuration already exists for 57838016001; please delete the configuration first, or update it instead.
 *
 * @apiErrorExample {json} 409 Error Response
 *    HTTP/1.1 404 NOT_FOUND
 *    [
 *        {
 *            "error_code": "NOT_AUTHORIZED",
 *            "message": "Credentials are required to access this resource."
 *        }
 *    ]
 * @apiErrorExample {html} 404 Error Response
 *    HTTP/1.1 404 NOT_FOUND
 *      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
*    <title>Error 404 NOT_FOUND</title>
*
HTTP ERROR 404

Problem accessing /v1/accounts/57838016001/configurtion. Reason:
 NOT_FOUND

*

* @apiErrorExample {html} 400 BAD_REQUEST
*     HTTP/1.1 400 BAD_REQUEST
*       <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
*     <title>Error 400 Unexpected character ('d' (code 100)): was expecting a colon to separate field name and value</title>
*
HTTP ERROR 400

Problem accessing /v1/accounts/57838016001/configuration. Reason:
 Unexpected character ('d' (code 100)): was expecting a colon to separate field name and value

*

*
* @apiErrorExample {json} 409 CONFLICT
*    HTTP/1.1 409 CONFLICT
*    [
*        {
*            "code": "CONFLICT",
*            "message": "Account configuration already exists for 57838016001; please delete the configuration first, or update it instead."
*        }
*    ]
 *
 */
<commit_msg>cleanup<commit_after>// get default profile

/**
 * @api {get} /accounts/:account_id/configuration Get Default Profile
 * @apiName Get Default Profile
 * @apiGroup Account Configuration
 * @apiVersion 1.0.0
 *
 * @apiDescription Get the default ingest profile for the account.
 *
 * @apiHeader {String} Content-Type Content-Type: application/json
 * @apiHeader {String} Authorization Authorization: Bearer access_token (see [Getting Access Tokens](https://support.brightcove.com/getting-access-tokens))
 *
 * @apiParam {String} account_id Video Cloud account ID
 *
 * @apiParamExample {json} Get Default Profile Example:
 *     https://ingestion.api.brightcove.com/v1/accounts/57838016001/configuration
 *
 * @apiSuccess (200) {Number} account_id Video Cloud account id
 * @apiSuccess (200) {String} id configuration id
 * @apiSuccess (200) {String} default_profile_id profile name for video-on-demand
 * @apiSuccess (200) {String} default_live_profile_id default profile name for live streams
 * @apiSuccess (200) {Number} date_created when the profile was created (epoch time in milliseconds)
 * @apiSuccess (200) {Number} date_last_modified when the profile was last modified (epoch time in milliseconds)
 * @apiSuccess (200) {Number} max_profile_count maximum number of custom profiles for the account
 * @apiSuccess (200) {Number} max_rendition_count maximum number of renditions per profile
 * @apiSuccess (200) {Number} version system-managed version number
 *
 * @apiSuccessExample {object} Success Response:
 *    HTTP/1.1 200 OK
 *    {
 *        "account_id": 57838016001,
 *        "date_created": 1442409154636,
 *        "date_last_modified": 1442409154636,
 *        "default_live_profile_id": "Live - Standard",
 *        "default_profile_id": "screencast-1280",
 *        "id": "55525f84e4b08e946aa03281",
 *        "max_profile_count": 10,
 *        "max_rendition_count": 20,
 *        "version": 1442409154636
 *    }
 *
 * @apiError (Error 4xx) {array} NOT_AUTHORIZED 401: Credentials are required to access this resource
 * @apiError (Error 4xx) {string} NOT_FOUND 404: The api couldn't find the resource you requested
 *
 * @apiErrorExample {array} 409 Error Response
 *    HTTP/1.1 404 NOT_FOUND
 *    [
 *        {
 *            "error_code": "NOT_AUTHORIZED",
 *            "message": "Credentials are required to access this resource."
 *        }
 *    ]
 *
 * @apiErrorExample {string} 404 Error Response
 *    HTTP/1.1 404 NOT_FOUND
 *      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
*    <title>Error 404 NOT_FOUND</title>
*
HTTP ERROR 404

Problem accessing /v1/accounts/57838016001/configurtion. Reason:
 NOT_FOUND

*
 *
 */

// set default profile

/**
 * @api {post} /accounts/:account_id/configuration Set Default Profile
 * @apiName Set Default Profile
 * @apiGroup Account Configuration
 * @apiVersion 1.0.0
 *
 * @apiDescription Sets an ingest profile as the default for the account.
 *
 * @apiHeader {String} Content-Type Content-Type: application/json
 * @apiHeader {String} Authorization Authorization: Bearer access_token (see [Getting Access Tokens](https://support.brightcove.com/getting-access-tokens))
 *
 * @apiParam {String} account_id Video Cloud account ID
 * @apiParam (Request Body Fields) {Number} account_id Video Cloud account ID
 * @apiParam (Request Body Fields) {String} default_profile_id The id or name of the profile you want to set as the default
 * @apiParam (Request Body Fields) {String} [default_live_profile_id] The id or name of the live profile you want to set as the default
 *
 * @apiParamExample {object} Set Default Profile Example:
 *     {
 *         "account_id": 57838016001,
 *         "default_profile_id": "high-resolution"
 *     }
 *
 * @apiSuccess (200) {Number} account_id Video Cloud account id
 * @apiSuccess (200) {String} id configuration id
 * @apiSuccess (200) {String} default_profile_id profile name for video-on-demand
 * @apiSuccess (200) {String} default_live_profile_id default profile name for live streams
 * @apiSuccess (200) {Integer} date_created when the profile was created (epoch time in milliseconds)
 * @apiSuccess (200) {Integer} date_last_modified when the profile was last modified (epoch time in milliseconds)
 * @apiSuccess (200) {Integer} max_profile_count maximum number of custom profiles for the account
 * @apiSuccess (200) {Integer} max_rendition_count maximum number of renditions per profile
 * @apiSuccess (200) {Number} version system-managed version number
 *
 * @apiSuccessExample {json} Success Response:
 *    HTTP/1.1 200 OK
 *    {
 *        "account_id": 57838016001,
 *        "date_created": 1443727850896,
 *        "date_last_modified": 1443727850896,
 *        "default_live_profile_id": "Live - Standard",
 *        "default_profile_id": "high-resolution",
 *        "id": "55525f84e4b08e946aa03281",
 *        "max_profile_count": 10,
 *        "max_rendition_count": 20,
 *        "version": 1443727850896
 *    }
 *
 * @apiError (Error 4xx) {array} NOT_AUTHORIZED 401: Credentials are required to access this resource.
 * @apiError (Error 4xx) {string} NOT_FOUND 404: The api couldn't find the resource you requested
 * @apiError (Error 4xx) {string} BAD_REQUEST 400: The JSON was not valid
 * @apiError (Error 4xx) {array} CONFLICT 409: Account configuration already exists for 57838016001; please delete the configuration first, or update it instead.
 *
 * @apiErrorExample {array} 401 Error Response
 *    HTTP/1.1 401 NOT_AUTHORIZED
 *    [
 *        {
 *            "error_code": "NOT_AUTHORIZED",
 *            "message": "Credentials are required to access this resource."
 *        }
 *    ]
 * @apiErrorExample {string} 404 Error Response
 *    HTTP/1.1 404 NOT_FOUND
 *      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
*    <title>Error 404 NOT_FOUND</title>
*
HTTP ERROR 404

Problem accessing /v1/accounts/57838016001/configurtion. Reason:
 NOT_FOUND

*
* @apiErrorExample {string} 400 BAD_REQUEST
*     HTTP/1.1 400 BAD_REQUEST
*       <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
*     <title>Error 400 Unexpected character ('d' (code 100)): was expecting a colon to separate field name and value</title>
*
HTTP ERROR 400

Problem accessing /v1/accounts/57838016001/configuration. Reason:
 Unexpected character ('d' (code 100)): was expecting a colon to separate field name and value

*
*
* @apiErrorExample {array} 409 CONFLICT
*    HTTP/1.1 409 CONFLICT
*    [
*        {
*            "code": "CONFLICT",
*            "message": "Account configuration already exists for 57838016001; please delete the configuration first, or update it instead."
*        }
*    ]
*
 */

// update default profile

/**
 * @api {put} /accounts/:account_id/configuration Update Default Profile
 * @apiName Update Default Profile
 * @apiGroup Account Configuration
 * @apiVersion 1.0.0
 *
 * @apiDescription Updates the default ingest profile for the account.
 *
 * @apiHeader {String} Content-Type Content-Type: application/json
 * @apiHeader {String} Authorization Authorization: Bearer access_token (see [Getting Access Tokens](https://support.brightcove.com/getting-access-tokens))
 *
 * @apiParam {String} account_id Video Cloud account ID
 * @apiParam (Request Body Fields) {Number} account_id Video Cloud account ID
 * @apiParam (Request Body Fields) {String} id the configuration id (if you don't have it, make a GET request to get it)
 * @apiParam (Request Body Fields) {String} default_profile_id The id or name of the profile you want to set as the default
 * @apiParam (Request Body Fields) {String} [default_live_profile_id] The id or name of the live profile you want to set as the default
 *
 * @apiParamExample {object} Update Default Profile Example:
 *     {
 *         "account_id": 57838016001,
 *         "default_profile_id": "high-resolution"
 *     }
 *
 * @apiSuccess (200) {Number} account_id Video Cloud account id
 * @apiSuccess (200) {String} id configuration id
 * @apiSuccess (200) {String} default_profile_id profile name for video-on-demand
 * @apiSuccess (200) {String} default_live_profile_id default profile name for live streams
 * @apiSuccess (200) {Integer} date_created when the profile was created (epoch time in milliseconds)
 * @apiSuccess (200) {Integer} date_last_modified when the profile was last modified (epoch time in milliseconds)
 * @apiSuccess (200) {Integer} max_profile_count maximum number of custom profiles for the account
 * @apiSuccess (200) {Integer} max_rendition_count maximum number of renditions per profile
 * @apiSuccess (200) {Number} version system-managed version number
 *
 * @apiSuccessExample {object} Success Response:
 *    HTTP/1.1 200 OK
 *    {
 *        "account_id": 57838016001,
 *        "date_created": 1443727850896,
 *        "date_last_modified": 1443727850896,
 *        "default_live_profile_id": "Live - Standard",
 *        "default_profile_id": "high-resolution",
 *        "id": "55525f84e4b08e946aa03281",
 *        "max_profile_count": 10,
 *        "max_rendition_count": 20,
 *        "version": 1443727850896
 *    }
 *
 * @apiError (Error 4xx) {array} NOT_AUTHORIZED 401: Credentials are required to access this resource.
 * @apiError (Error 4xx) {string} NOT_FOUND 404: The api couldn't find the resource you requested
 * @apiError (Error 4xx) {string} BAD_REQUEST 400: The JSON was not valid
 * @apiError (Error 4xx) {array} CONFLICT 409: Account configuration already exists for 57838016001; please delete the configuration first, or update it instead.
 *
 * @apiErrorExample {array} 409 Error Response
 *    HTTP/1.1 404 NOT_FOUND
 *    [
 *        {
 *            "error_code": "NOT_AUTHORIZED",
 *            "message": "Credentials are required to access this resource."
 *        }
 *    ]
 * @apiErrorExample {string} 404 Error Response
 *    HTTP/1.1 404 NOT_FOUND
 *      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
*    <title>Error 404 NOT_FOUND</title>
*
HTTP ERROR 404

Problem accessing /v1/accounts/57838016001/configurtion. Reason:
 NOT_FOUND

*
* @apiErrorExample {string} 400 BAD_REQUEST
*     HTTP/1.1 400 BAD_REQUEST
*       <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
*     <title>Error 400 Unexpected character ('d' (code 100)): was expecting a colon to separate field name and value</title>
*
HTTP ERROR 400

Problem accessing /v1/accounts/57838016001/configuration. Reason:
 Unexpected character ('d' (code 100)): was expecting a colon to separate field name and value

*
*
* @apiErrorExample {array} 409 CONFLICT
*    HTTP/1.1 409 CONFLICT
*    [
*        {
*            "code": "CONFLICT",
*            "message": "Account configuration already exists for 57838016001; please delete the configuration first, or update it instead."
*        }
*    ]
 *
 */
<|endoftext|>