<commit_before>

import React, {
    Component,
} from 'react'
import {
    View,
    StyleSheet,
    Alert,
} from 'react-native'

import Barcode from 'react-native-smart-barcode'
import TimerEnhance from 'react-native-smart-timer-enhance'

class BarcodeTest extends Component {

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            viewAppear: false,
        };
    }

    render() {

        return (
            <View style={{flex: 1, backgroundColor: 'black',}}>
                {this.state.viewAppear ? <Barcode style={{flex: 1, }}
                                                  ref={ component => this._barCode = component }
                                                  onBarCodeRead={this._onBarCodeRead}/> : null}
            </View>
        )
    }

    componentDidMount() {
        let viewAppearCallBack = (event) => {
            this.setTimeout( () => {
                this.setState({
                    viewAppear: true,
                })
            }, 255)

        }
        this._listeners = [
            this.props.navigator.navigationContext.addListener('didfocus', viewAppearCallBack)
        ]

    }

    componentWillUnmount () {
        this._listeners && this._listeners.forEach(listener => listener.remove());
    }

    _onBarCodeRead = (e) => {
        console.log(`e.nativeEvent.data.type = ${e.nativeEvent.data.type}, e.nativeEvent.data.code = ${e.nativeEvent.data.code}`)
        this._stopScan()
        Alert.alert(e.nativeEvent.data.type, e.nativeEvent.data.code, [
            {text: 'OK', onPress: () => this._startScan()},
        ])
    }

    _startScan = (e) => {
        this._barCode.startScan()
    }

    _stopScan = (e) => {
        this._barCode.stopScan()
    }

}

export default TimerEnhance(BarcodeTest)<commit_msg>added ActivityIndicator before BarCodeView is loaded<commit_after>import React, {
    Component,
} from 'react'
import {
    View,
    StyleSheet,
    Alert,
    ActivityIndicator,
    ProgressBarAndroid,
    ActivityIndicatorIOS,
    Dimensions,
} from 'react-native'

import Barcode from 'react-native-smart-barcode'
import TimerEnhance from 'react-native-smart-timer-enhance'

//const { width: deviceWidth, height: deviceHeight } = Dimensions.get('window')

class BarcodeTest extends Component {

    // 构造
    constructor (props) {
        super(props);
        // 初始状态
        this.state = {
            viewAppear: false,
        };
    }

    render () {

        return (
            <View style={{flex: 1, backgroundColor: 'black', justifyContent: 'center', alignItems: 'center',}}>
                {this.state.viewAppear ? <Barcode style={{flex: 1, alignSelf: 'stretch', }}
                                                  ref={ component => this._barCode = component }
                                                  onBarCodeRead={this._onBarCodeRead}/> : null}

                {!this.state.viewAppear ? this._renderActivityIndicator() : null}
            </View>
        )
    }
//
//{!this.state.viewAppear ?
//<View style={{ position: 'absolute', left: 0, top: 0, width: deviceWidth, deviceHeight: deviceHeight, justifyContent: 'center', alignItems: 'center'}}>
//{this._renderActivityIndicator()}
//</View> : null}

    componentDidMount () {
        let viewAppearCallBack = (event) => {
            this.setTimeout(() => {
                this.setState({
                    viewAppear: true,
                })
            }, 255)

        }
        this._listeners = [
            this.props.navigator.navigationContext.addListener('didfocus', viewAppearCallBack)
        ]

    }

    componentWillUnmount () {
        this._listeners && this._listeners.forEach(listener => listener.remove());
    }

    _onBarCodeRead = (e) => {
        console.log(`e.nativeEvent.data.type = ${e.nativeEvent.data.type}, e.nativeEvent.data.code = ${e.nativeEvent.data.code}`)
        this._stopScan()
        Alert.alert(e.nativeEvent.data.type, e.nativeEvent.data.code, [
            { text: 'OK', onPress: () => this._startScan() },
        ])
    }

    _startScan = (e) => {
        this._barCode.startScan()
    }

    _stopScan = (e) => {
        this._barCode.stopScan()
    }

    _renderActivityIndicator () {
        return ActivityIndicator ? (
            <ActivityIndicator
                style={{position: 'relative', left: 1, top: 1,}}
                animating={true}
                size={'large'}/>
        ) : Platform.OS == 'android' ?
            (
                <ProgressBarAndroid
                    styleAttr={'large'}/>

            ) : (
            <ActivityIndicatorIOS
                animating={true}
                size={'large'}/>
        )
    }
}

export default TimerEnhance(BarcodeTest)<|endoftext|>


<commit_before>$(document).ready(function(){
    attachFormEventHandlers($("body"));
});

// Adds hidden input fields indicating the attributes' order.
// This method works both for a Type's attributes and for
// an AA's values, as both rely on an input named attr-name-*
function addAttributeOrderFields(form){
    var name_fields = form.find("input[name^='attr-name-']:not([name='attr-name-X'])");
    for (var i=0; i<name_fields.length; i++){
        var field_id = name_fields.get(i).name.substring(10);
        var order_field = $('<input />');
        order_field.attr('type', 'hidden');
        order_field.attr('name', 'attr-order-' + field_id);
        order_field.attr('value', i+1);
        form.append(order_field);
    }
}

function attachFormEventHandlers(context){
    // Attributes
    context.find("tr.addattr").click(function() {
        return addAttributeFromPhantom(context, $(this).parents("tr.phantom"));
    });
    context.find("tr.addattr input").focus(function() {
        return addAttributeFromPhantom(context, $(this).parents("tr.phantom"));
    });
    context.find("a.delattr").click(delAttribute);

    // Values
    context.find("tr.addvalue").click(function() {
        return addValueFromPhantom(context, $(this).parents("tr.phantom"))
    });
    context.find("tr.addvalue input").focus(function() {
        return addValueFromPhantom(context, $(this).parents("tr.phantom"));
    });
    context.find("a.delvalue").click(delAttribute);
    context.find("a.tomultiline").click(toMultiline);
    context.find("a.touniline").click(toUniline);
    context.find("a.reorder-down,a.reorder-up").click(reorder);

    context.find("#artifact-form").submit(function(e){
        addAttributeOrderFields($("#artifact-form"));
    });
    context.find("#type-form").submit(function(e){
        addAttributeOrderFields($("#type-form"));
    });
    $("input#spec").autocomplete(
        {source: function(request, callback){
            Requests.searchSpecNames([request.term], function(data){
                callback(data);
            });
        }}
    );
}

function addAttributeFromPhantom(context, phantom){
    var name = phantom.find("input[name^='attr-name-']").attr("value");
    phantom.hide();
    var inputs = addAttribute(context, name);
    var name_input = inputs[0];
    var type_input = inputs[1];
    if (phantom.hasClass("suggestion")){
         phantom.remove();
        type_input.focus();
    } else {
        phantom.show(1000);
        name_input.focus();
        name_input.select();
    }
    return false;
}

function addAttribute(context, name){
    var newid = uuid.v4();
    var copy = context.find("tr.attribute.prototype").clone(true);
    copy.removeClass('prototype');
    var name_input = copy.find("input[name^='attr-name-']");
    name_input.attr("name", "attr-name-" + newid);
    name_input.attr("value", name);
    var type_input = copy.find("select[name^='attr-type-']");
    type_input.attr("name", "attr-type-" + newid);
    type_input.attr("value", "");
    var multiplicity_input = copy.find("select[name^='attr-multiplicity-']");
    multiplicity_input.attr("name", "attr-multiplicity-" + newid);
    multiplicity_input.attr("value", "");
    context.find("table.attributes tr:not(.phantom):last").after(copy);
    return [name_input, type_input, multiplicity_input];
}

function delAttribute(){
    $(this).parents("tr.attribute").remove();
    return false;
}

function addValueFromPhantom(context, phantom){
    var name = phantom.find("input[name^='attr-name-']").attr("value");
    var value = phantom.find("input[name^='attr-value-']").attr("value");
    phantom.hide();
    var inputs = addValue(context, name, value);
    var name_input = inputs[0];
    var value_input = inputs[1];
    if (phantom.hasClass("suggestion")){
         phantom.remove();
         value_input.focus();
    } else {
        phantom.show(1000);
        name_input.focus();
        name_input.select();
    }
    return false;
}

function addValue(context, name, val){
    var newid = uuid.v4();
    var copy = context.find("tr.attribute.prototype").clone(true);
    copy.removeClass('prototype');
    var name_input = copy.find("input[name^='attr-name-']");
    name_input.attr("name", "attr-name-" + newid);
    name_input.attr("value", name);
    var value_input = copy.find("input[name^='attr-value-']");
    value_input.attr("name", "attr-value-" + newid);
    value_input.attr("value", val);
    var default_input = copy.find("input[name^='default']");
    default_input.attr("value", newid);
    if ($('form#artifact-form input[name=default]:checked').length==0)
        default_input.attr('checked', true);
    context.find("table.attributes tr:not(.phantom):last").after(copy);
    return [name_input, value_input];
}

function toMultiline(){
    var input = $(this).parent().find("input");
    var textarea = $("<textarea/>")
        .attr("name", input.attr("name"))
        .text(input.val());
    input.after(textarea).remove();
    var link = $(this).parent().find("a")
        .clone()
        .attr("title", "Collapse to single-line field")
        .removeClass("tomultiline")
        .addClass("touniline")
        .click(toUniline);
    $(this)
        .after(link)
        .remove();
    return false;
}

function toUniline(){
    if (!confirm("You may loose wiki markup and line breaks, are you sure?"))
        return false;

    var textarea = $(this).parent().find("textarea");
    var input = $("<input/>")
        .attr("type", "text")
        .attr("name", textarea.attr("name"))
        .val(textarea.text());
    textarea.after(input).remove();
    var link = $(this).parent().find("a")
        .clone()
        .attr("title", "Expand to multi-line field")
        .removeClass("touniline")
        .addClass("tomultiline")
        .click(toMultiline);
    $(this)
        .after(link)
        .remove();
    return false;
}

function reorder(){
    var table = $(this).parents("table");
    var moving_row = $(this).parents("tr:first");
    if ($(this).is(".reorder-up")) {
        if (!moving_row.is(table.find("tr.attribute:not(.prototype):not(.addvalue,.addattr):first"))){
            moving_row.hide();
            moving_row.insertBefore(moving_row.prev());
            moving_row.show(1500);
        }
    } else {
        if (!moving_row.is(table.find("tr.attribute:not(.prototype):not(.addvalue,.addattr):last"))){
            moving_row.hide();
            moving_row.insertAfter(moving_row.next());
            moving_row.show(1500);
        }
    }
    return false;
}<commit_msg>Fixed bug that allowed to reorder attributes to above a readonly one (for types).<commit_after>$(document).ready(function(){
    attachFormEventHandlers($("body"));
});

// Adds hidden input fields indicating the attributes' order.
// This method works both for a Type's attributes and for
// an AA's values, as both rely on an input named attr-name-*
function addAttributeOrderFields(form){
    var name_fields = form.find("input[name^='attr-name-']:not([name='attr-name-X'])");
    for (var i=0; i<name_fields.length; i++){
        var field_id = name_fields.get(i).name.substring(10);
        var order_field = $('<input />');
        order_field.attr('type', 'hidden');
        order_field.attr('name', 'attr-order-' + field_id);
        order_field.attr('value', i+1);
        form.append(order_field);
    }
}

function attachFormEventHandlers(context){
    // Attributes
    context.find("tr.addattr").click(function() {
        return addAttributeFromPhantom(context, $(this).parents("tr.phantom"));
    });
    context.find("tr.addattr input").focus(function() {
        return addAttributeFromPhantom(context, $(this).parents("tr.phantom"));
    });
    context.find("a.delattr").click(delAttribute);

    // Values
    context.find("tr.addvalue").click(function() {
        return addValueFromPhantom(context, $(this).parents("tr.phantom"))
    });
    context.find("tr.addvalue input").focus(function() {
        return addValueFromPhantom(context, $(this).parents("tr.phantom"));
    });
    context.find("a.delvalue").click(delAttribute);
    context.find("a.tomultiline").click(toMultiline);
    context.find("a.touniline").click(toUniline);
    context.find("a.reorder-down,a.reorder-up").click(reorder);

    context.find("#artifact-form").submit(function(e){
        addAttributeOrderFields($("#artifact-form"));
    });
    context.find("#type-form").submit(function(e){
        addAttributeOrderFields($("#type-form"));
    });
    $("input#spec").autocomplete(
        {source: function(request, callback){
            Requests.searchSpecNames([request.term], function(data){
                callback(data);
            });
        }}
    );
}

function addAttributeFromPhantom(context, phantom){
    var name = phantom.find("input[name^='attr-name-']").attr("value");
    phantom.hide();
    var inputs = addAttribute(context, name);
    var name_input = inputs[0];
    var type_input = inputs[1];
    if (phantom.hasClass("suggestion")){
         phantom.remove();
        type_input.focus();
    } else {
        phantom.show(1000);
        name_input.focus();
        name_input.select();
    }
    return false;
}

function addAttribute(context, name){
    var newid = uuid.v4();
    var copy = context.find("tr.attribute.prototype").clone(true);
    copy.removeClass('prototype');
    var name_input = copy.find("input[name^='attr-name-']");
    name_input.attr("name", "attr-name-" + newid);
    name_input.attr("value", name);
    var type_input = copy.find("select[name^='attr-type-']");
    type_input.attr("name", "attr-type-" + newid);
    type_input.attr("value", "");
    var multiplicity_input = copy.find("select[name^='attr-multiplicity-']");
    multiplicity_input.attr("name", "attr-multiplicity-" + newid);
    multiplicity_input.attr("value", "");
    context.find("table.attributes tr:not(.phantom):last").after(copy);
    return [name_input, type_input, multiplicity_input];
}

function delAttribute(){
    $(this).parents("tr.attribute").remove();
    return false;
}

function addValueFromPhantom(context, phantom){
    var name = phantom.find("input[name^='attr-name-']").attr("value");
    var value = phantom.find("input[name^='attr-value-']").attr("value");
    phantom.hide();
    var inputs = addValue(context, name, value);
    var name_input = inputs[0];
    var value_input = inputs[1];
    if (phantom.hasClass("suggestion")){
         phantom.remove();
         value_input.focus();
    } else {
        phantom.show(1000);
        name_input.focus();
        name_input.select();
    }
    return false;
}

function addValue(context, name, val){
    var newid = uuid.v4();
    var copy = context.find("tr.attribute.prototype").clone(true);
    copy.removeClass('prototype');
    var name_input = copy.find("input[name^='attr-name-']");
    name_input.attr("name", "attr-name-" + newid);
    name_input.attr("value", name);
    var value_input = copy.find("input[name^='attr-value-']");
    value_input.attr("name", "attr-value-" + newid);
    value_input.attr("value", val);
    var default_input = copy.find("input[name^='default']");
    default_input.attr("value", newid);
    if ($('form#artifact-form input[name=default]:checked').length==0)
        default_input.attr('checked', true);
    context.find("table.attributes tr:not(.phantom):last").after(copy);
    return [name_input, value_input];
}

function toMultiline(){
    var input = $(this).parent().find("input");
    var textarea = $("<textarea/>")
        .attr("name", input.attr("name"))
        .text(input.val());
    input.after(textarea).remove();
    var link = $(this).parent().find("a")
        .clone()
        .attr("title", "Collapse to single-line field")
        .removeClass("tomultiline")
        .addClass("touniline")
        .click(toUniline);
    $(this)
        .after(link)
        .remove();
    return false;
}

function toUniline(){
    if (!confirm("You may loose wiki markup and line breaks, are you sure?"))
        return false;

    var textarea = $(this).parent().find("textarea");
    var input = $("<input/>")
        .attr("type", "text")
        .attr("name", textarea.attr("name"))
        .val(textarea.text());
    textarea.after(input).remove();
    var link = $(this).parent().find("a")
        .clone()
        .attr("title", "Expand to multi-line field")
        .removeClass("touniline")
        .addClass("tomultiline")
        .click(toMultiline);
    $(this)
        .after(link)
        .remove();
    return false;
}

function reorder(){
    var table = $(this).parents("table");
    var moving_row = $(this).parents("tr:first");
    if ($(this).is(".reorder-up")) {
        if (!moving_row.is(table.find("tr.attribute:not(.prototype):not(.addvalue,.addattr):not(:has(td.readonly)):first"))){
            moving_row.hide();
            moving_row.insertBefore(moving_row.prev());
            moving_row.show(1500);
        }
    } else {
        if (!moving_row.is(table.find("tr.attribute:not(.prototype):not(.addvalue,.addattr):not(:has(td.readonly)):last"))){
            moving_row.hide();
            moving_row.insertAfter(moving_row.next());
            moving_row.show(1500);
        }
    }
    return false;
}<|endoftext|>


<commit_before>'use strict';

const registration = require('../../../lib/plugins/file/markdown');
const bodySplitterRegistration = require('../../../lib/plugins/helpers/body_splitter');
let bodySplitter;

bodySplitterRegistration((a, b, fn) => {
  bodySplitter = fn;
});

describe('makrdown file processor', () => {
  let markdownProcessor;

  beforeAll(() => {
    registration((type, name, extensions, fn) => {
      markdownProcessor = fn;
    });
  });

  const markdown = `
# Title
`;

  const markdownWithFrontMatter = `---
foo: 'bar'
---

# Title
`;

  const markdownWithSections = `
---first---
# First section

---last---
# Last section
`;

  const markdownWithFrontMatterAndSections = `---
foo: 'bar'
---

---first---
# First section

---last---
# Last section
`;

  const markdownWithCode = `
\`\`\`js
const foo = 'bar';
\`\`\`
`;

  it('should return rendered fileContents if we are dealing with a directory', () => {
    const res = markdownProcessor(markdown, { isDirectory: true }, {});

    expect(res).toBe('
Title
\n');
  });

  it('should return the front matter as meta attribute', () => {
    const res = markdownProcessor(markdownWithFrontMatter, {}, { bodySplitter });

    expect(res.meta).toEqual({ foo: 'bar' });
  });

  it('should return the contents for the file in the content.content property if we have no sections', () => {
    const res = markdownProcessor(markdownWithFrontMatter, {}, { bodySplitter });

    expect(res.content).toEqual({ content: '
Title
\n' });
  });

  it('should return the sections in the content property', () => {
    const res = markdownProcessor(markdownWithSections, {}, { bodySplitter });

    expect(res.content.first).toEqual('
First section
\n');
    expect(res.content.last).toEqual('
Last section
\n');
  });

  it('should be able to work with front matter and sections', () => {
    const res = markdownProcessor(
      markdownWithFrontMatterAndSections, {}, { bodySplitter }
    );

    expect(res.meta).toEqual({ foo: 'bar' });
    expect(res.content.first).toEqual('
First section
\n');
    expect(res.content.last).toEqual('
Last section
\n');
  });

  it('should not add highlightjs elements if it not explicitly set in the options', () => {
    const res = markdownProcessor(markdownWithCode, {}, { bodySplitter });

    expect(res.content.content).toEqual('
const foo = \'bar\';\n
\n');
  });

  it('should add highlightjs elements if codeHighlight is set', () => {
    const res = markdownProcessor(markdownWithCode, { codeHighlight: true }, { bodySplitter });

    expect(res.content.content).toEqual('
const' +
      'foo = \'bar\';\n
\n');
  });

  it('should not add highlightjs elements if the code language is not supported by highlightjs', () => {
    const markdownWithCode = `
\`\`\`foo
const bar = 'foo';
\`\`\`
`;
    const res = markdownProcessor(markdownWithCode, { codeHighlight: true }, { bodySplitter });

    expect(res.content.content).toEqual('
const bar = \'foo\';\n
\n');
  });
});
<commit_msg>fix spec<commit_after>'use strict';

const registration = require('../../../lib/plugins/file/markdown');
const bodySplitterRegistration = require('../../../lib/plugins/helpers/body_splitter');
let bodySplitter;

bodySplitterRegistration((a, b, fn) => {
  bodySplitter = fn;
});

describe('makrdown file processor', () => {
  let markdownProcessor;

  beforeAll(() => {
    registration((type, name, extensions, fn) => {
      markdownProcessor = fn;
    });
  });

  const markdown = `
# Title
`;

  const markdownWithFrontMatter = `---
foo: 'bar'
---

# Title
`;

  const markdownWithSections = `
---first---
# First section

---last---
# Last section
`;

  const markdownWithFrontMatterAndSections = `---
foo: 'bar'
---

---first---
# First section

---last---
# Last section
`;

  const markdownWithCode = `
\`\`\`js
const foo = 'bar';
\`\`\`
`;

  it('should return rendered fileContents if we are dealing with a directory', () => {
    const res = markdownProcessor(markdown, { isDirectory: true }, {});

    expect(res).toBe('
Title
\n');
  });

  it('should return the front matter as meta attribute', () => {
    const res = markdownProcessor(markdownWithFrontMatter, {}, { bodySplitter });

    expect(res.meta).toEqual({ foo: 'bar' });
  });

  it('should return the contents for the file in the content.content property if we have no sections', () => {
    const res = markdownProcessor(markdownWithFrontMatter, {}, { bodySplitter });

    expect(res.content).toEqual({ content: '
Title
\n' });
  });

  it('should return the sections in the content property', () => {
    const res = markdownProcessor(markdownWithSections, {}, { bodySplitter });

    expect(res.content.first).toEqual('
First section
\n');
    expect(res.content.last).toEqual('
Last section
\n');
  });

  it('should be able to work with front matter and sections', () => {
    const res = markdownProcessor(
      markdownWithFrontMatterAndSections, {}, { bodySplitter }
    );

    expect(res.meta).toEqual({ foo: 'bar' });
    expect(res.content.first).toEqual('
First section
\n');
    expect(res.content.last).toEqual('
Last section
\n');
  });

  it('should not add highlightjs elements if it not explicitly set in the options', () => {
    const res = markdownProcessor(markdownWithCode, {}, { bodySplitter });

    expect(res.content.content).toEqual('
const foo = \'bar\';\n
\n');
  });

  it('should add highlightjs elements if codeHighlight is set', () => {
    const res = markdownProcessor(markdownWithCode, { codeHighlight: true }, { bodySplitter });

    expect(res.content.content).toEqual('
const ' +
      'foo = \'bar\';\n
\n');
  });

  it('should not add highlightjs elements if the code language is not supported by highlightjs', () => {
    const markdownWithCode = `
\`\`\`foo
const bar = 'foo';
\`\`\`
`;
    const res = markdownProcessor(markdownWithCode, { codeHighlight: true }, { bodySplitter });

    expect(res.content.content).toEqual('
const bar = \'foo\';\n
\n');
  });
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

define(['require', 'elementUtils', 'lodash'],
    function (require, ElementUtils, _) {

        /**
         * @class AppData
         * @constructor
         * @class AppData  Holds the data for given Siddhi app
         */
        var AppData = function () {
            // initiates the collections
            this.streamList = [];
            this.tableList = [];
            this.windowList = [];
            this.triggerList = [];
            this.aggregationList = [];
            this.functionList = [];
            this.partitionList = [];
            this.sourceList = [];
            this.sinkList = [];
            this.queryLists = {
                WINDOW_FILTER_PROJECTION: [],
                PATTERN: [],
                SEQUENCE: [],
                JOIN: []
            };
            // finalElementCount --> Number of elements that exist on the canvas at the time of saving the model
            this.finalElementCount = 0;

        };

        AppData.prototype.addStream = function (stream) {
            this.streamList.push(stream);
        };

        AppData.prototype.addTable = function (table) {
            this.tableList.push(table);
        };

        AppData.prototype.addWindow = function (window) {
            this.windowList.push(window);
        };

        AppData.prototype.addTrigger = function (trigger) {
            this.triggerList.push(trigger);
        };

        AppData.prototype.addAggregation = function (aggregation) {
            this.aggregationList.push(aggregation);
        };

        AppData.prototype.addFunction = function (functionObject) {
            this.functionList.push(functionObject);
        };

        AppData.prototype.addWindowFilterProjectionQuery = function (windowFilterProjectionQuery) {
            this.queryLists.WINDOW_FILTER_PROJECTION.push(windowFilterProjectionQuery);
        };

        AppData.prototype.addPatternQuery = function (patternQuery) {
            this.queryLists.PATTERN.push(patternQuery);
        };

        AppData.prototype.addSequenceQuery = function (sequenceQuery) {
            this.queryLists.SEQUENCE.push(sequenceQuery);
        };

        AppData.prototype.addJoinQuery = function (joinQuery) {
            this.queryLists.JOIN.push(joinQuery);
        };

        AppData.prototype.addPartition = function (partition) {
            this.partitionList.push(partition);
        };

        AppData.prototype.addSource = function (source) {
            this.sourceList.push(source);
        };

        AppData.prototype.addSink = function (sink) {
            this.sinkList.push(sink);
        };

        AppData.prototype.removeStream = function (streamId) {
            ElementUtils.prototype.removeElement(this.streamList, streamId);
        };

        AppData.prototype.removeTable = function (tableId) {
            ElementUtils.prototype.removeElement(this.tableList, tableId);
        };

        AppData.prototype.removeWindow = function (windowId) {
            ElementUtils.prototype.removeElement(this.windowList, windowId);
        };

        AppData.prototype.removeTrigger = function (triggerId) {
            ElementUtils.prototype.removeElement(this.triggerList, triggerId);
        };

        AppData.prototype.removeAggregation = function (aggregationId) {
            ElementUtils.prototype.removeElement(this.aggregationList, aggregationId);
        };

        AppData.prototype.removeFunction = function (functionId) {
            ElementUtils.prototype.removeElement(this.functionList, functionId);
        };

        AppData.prototype.removeWindowFilterProjectionQuery = function (windowFilterProjectionQueryId) {
            ElementUtils.prototype
                .removeElement(this.queryLists.WINDOW_FILTER_PROJECTION, windowFilterProjectionQueryId);
        };

        AppData.prototype.removePatternQuery = function (patternQueryId) {
            ElementUtils.prototype.removeElement(this.queryLists.PATTERN, patternQueryId);
        };

        AppData.prototype.removeSequenceQuery = function (sequenceQueryId) {
            ElementUtils.prototype.removeElement(this.queryLists.SEQUENCE, sequenceQueryId);
        };

        AppData.prototype.removeJoinQuery = function (joinQueryId) {
            ElementUtils.prototype.removeElement(this.queryLists.JOIN, joinQueryId);
        };

        AppData.prototype.removePartition = function (partitionId) {
            ElementUtils.prototype.removeElement(this.partitionList, partitionId);
        };

        AppData.prototype.removeSource = function (sourceId) {
            ElementUtils.prototype.removeElement(this.sourceList, sourceId);
        };

        AppData.prototype.removeSink = function (sinkId) {
            ElementUtils.prototype.removeElement(this.sinkList, sinkId);
        };

        AppData.prototype.setFinalElementCount = function (finalElementCount) {
            this.finalElementCount = finalElementCount;
        };

        AppData.prototype.getStream = function (streamId) {
            return ElementUtils.prototype.getElement(this.streamList, streamId);
        };

        AppData.prototype.getTable = function (tableId) {
            return ElementUtils.prototype.getElement(this.tableList, tableId);
        };

        AppData.prototype.getWindow = function (windowId) {
            return ElementUtils.prototype.getElement(this.windowList, windowId);
        };

        AppData.prototype.getTrigger = function (triggerId) {
            return ElementUtils.prototype.getElement(this.triggerList, triggerId);
        };

        AppData.prototype.getAggregation = function (aggregationId) {
            return ElementUtils.prototype.getElement(this.aggregationList, aggregationId);
        };

        AppData.prototype.getFunction = function (functionId) {
            return ElementUtils.prototype.getElement(this.functionList, functionId);
        };

        AppData.prototype.getWindowFilterProjectionQuery = function (windowFilterProjectionQueryId) {
            return ElementUtils.prototype
                .getElement(this.queryLists.WINDOW_FILTER_PROJECTION, windowFilterProjectionQueryId);
        };

        AppData.prototype.getPatternQuery = function (patternQueryId) {
            return ElementUtils.prototype.getElement(this.queryLists.PATTERN, patternQueryId);
        };

        AppData.prototype.getSequenceQuery = function (sequenceQueryId) {
            return ElementUtils.prototype.getElement(this.queryLists.SEQUENCE, sequenceQueryId);
        };

        AppData.prototype.getJoinQuery = function (joinQueryId) {
            return ElementUtils.prototype.getElement(this.queryLists.JOIN, joinQueryId);
        };

        AppData.prototype.getPartition = function (partitionId) {
            return ElementUtils.prototype.getElement(this.partitionList, partitionId);
        };

        AppData.prototype.getSource = function (sourceId) {
            return ElementUtils.prototype.getElement(this.sourceList, sourceId);
        };

        AppData.prototype.getSink = function (sinkId) {
            return ElementUtils.prototype.getElement(this.sinkList, sinkId);
        };

        AppData.prototype.getStreamList = function () {
            return this.streamList;
        };

        AppData.prototype.getTableList = function () {
            return this.tableList;
        };

        AppData.prototype.getWindowList = function () {
            return this.windowList;
        };

        AppData.prototype.getTriggerList = function () {
            return this.triggerList;
        };

        AppData.prototype.getAggregationList = function () {
            return this.aggregationList;
        };

        AppData.prototype.getFunctionList = function () {
            return this.functionList;
        };

        AppData.prototype.getWindowFilterProjectionQueryList = function () {
            return this.queryLists.WINDOW_FILTER_PROJECTION;
        };

        AppData.prototype.getPatternQueryList = function () {
            return this.queryLists.PATTERN;
        };

        AppData.prototype.getSequenceQueryList = function () {
            return this.queryLists.SEQUENCE;
        };

        AppData.prototype.getJoinQueryList = function () {
            return this.queryLists.JOIN;
        };

        AppData.prototype.getPartitionList = function () {
            return this.partitionList;
        };

        AppData.prototype.getSourceList = function () {
            return this.sourceList;
        };

        AppData.prototype.getSinkList = function () {
            return this.sinkList;
        };

        AppData.prototype.getFinalElementCount = function () {
            return this.finalElementCount;
        };

        /**
         * @function Get the element by providing the element id
         * @param elementId id of the definition element
         * @param includeQueryTypes if true search in the queries as well
         * @param includeSourceAndSink if true search in the sinks and sources as well
         * @return requestedElement returns undefined if the requested element is not found
         */
        AppData.prototype.getDefinitionElementById = function (elementId, includeQueryTypes, includeSourceAndSink) {
            var self = this;
            var requestedElement = undefined;
            var streamList = self.streamList;
            var tableList = self.tableList;
            var windowList = self.windowList;
            var aggregationList = self.aggregationList;
            var functionList = self.functionList;
            var triggerList = self.triggerList;
            var windowFilterProjectionQueryList = self.queryLists.WINDOW_FILTER_PROJECTION;
            var patternQueryList = self.queryLists.PATTERN;
            var sequenceQueryList = self.queryLists.SEQUENCE;
            var joinQueryList = self.queryLists.JOIN;
            var sourceList = self.sourceList;
            var sinkList = self.sinkList;

            var lists = [streamList, tableList, windowList, aggregationList, functionList, triggerList];

            if (includeQueryTypes !== undefined && includeQueryTypes) {
                lists.push(windowFilterProjectionQueryList);
                lists.push(patternQueryList);
                lists.push(sequenceQueryList);
                lists.push(joinQueryList);
            }
            if (includeSourceAndSink !== undefined && includeSourceAndSink) {
                lists.push(sourceList);
                lists.push(sinkList);
            }

            _.forEach(lists, function (list) {
                _.forEach(list, function (element) {
                    if (element.getId() === elementId) {
                        var type = '';
                        if (list === streamList) {
                            type = 'STREAM';
                        } else if (list === tableList) {
                            type = 'TABLE';
                        } else if (list === windowList) {
                            type = 'WINDOW';
                        } else if (list === aggregationList) {
                            type = 'AGGREGATION';
                        } else if (list === functionList) {
                            type = 'FUNCTION';
                        } else if (list === triggerList) {
                            type = 'TRIGGER';
                        } else if (list === windowFilterProjectionQueryList) {
                            type = 'WINDOW_FILTER_PROJECTION_QUERY';
                        } else if (list === patternQueryList) {
                            type = 'PATTERN_QUERY';
                        } else if (list === sequenceQueryList) {
                            type = 'SEQUENCE_QUERY';
                        } else if (list === joinQueryList) {
                            type = 'JOIN_QUERY';
                        } else if (list === sourceList) {
                            type = 'SOURCE';
                        } else if (list === sinkList) {
                            type = 'SINK';
                        }
                        requestedElement = {
                            type: type,
                            element: element
                        };
                    }
                });
            });

            return requestedElement;
        };

        /**
         * @function Get the element by providing the element name
         * @param elementName name of the definition element
         * @param includeQueryTypes if true search in the queries as well
         * @return requestedElement returns undefined if the requested element is not found
         */
        AppData.prototype.getDefinitionElementByName = function (elementName, includeQueryTypes) {
            var self = this;
            var requestedElement = undefined;
            var streamList = self.streamList;
            var tableList = self.tableList;
            var windowList = self.windowList;
            var aggregationList = self.aggregationList;
            var functionList = self.functionList;
            var triggerList = self.triggerList;
            var windowFilterProjectionQueryList = self.queryLists.WINDOW_FILTER_PROJECTION;
            var patternQueryList = self.queryLists.PATTERN;
            var sequenceQueryList = self.queryLists.SEQUENCE;
            var joinQueryList = self.queryLists.JOIN;

            var listNames = [streamList, tableList, windowList, aggregationList, functionList, triggerList];

            if (includeQueryTypes !== undefined && includeQueryTypes) {
                listNames.push(windowFilterProjectionQueryList);
                listNames.push(patternQueryList);
                listNames.push(sequenceQueryList);
                listNames.push(joinQueryList);
            }

            _.forEach(listNames, function (list) {
                _.forEach(list, function (element) {
                    if (element.getName().toUpperCase() === elementName.toUpperCase()) {
                        var type = '';
                        if (list === streamList) {
                            type = 'STREAM';
                        } else if (list === tableList) {
                            type = 'TABLE';
                        } else if (list === windowList) {
                            type = 'WINDOW';
                        } else if (list === aggregationList) {
                            type = 'AGGREGATION';
                        } else if (list === functionList) {
                            type = 'FUNCTION';
                        } else if (list === triggerList) {
                            type = 'TRIGGER';
                        } else if (list === windowFilterProjectionQueryList) {
                            type = 'WINDOW_FILTER_PROJECTION_QUERY';
                        } else if (list === patternQueryList) {
                            type = 'PATTERN_QUERY';
                        } else if (list === sequenceQueryList) {
                            type = 'SEQUENCE_QUERY';
                        } else if (list === joinQueryList) {
                            type = 'JOIN_QUERY';
                        }
                        requestedElement = {
                            type: type,
                            element: element
                        };
                    }
                });
            });

            return requestedElement;
        };

        return AppData;
    });
<commit_msg>Improve utility methods to check streams and queries inside partition<commit_after>/**
 * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

define(['require', 'elementUtils', 'lodash'],
    function (require, ElementUtils, _) {

        /**
         * @class AppData
         * @constructor
         * @class AppData  Holds the data for given Siddhi app
         */
        var AppData = function () {
            // initiates the collections
            this.streamList = [];
            this.tableList = [];
            this.windowList = [];
            this.triggerList = [];
            this.aggregationList = [];
            this.functionList = [];
            this.partitionList = [];
            this.sourceList = [];
            this.sinkList = [];
            this.queryLists = {
                WINDOW_FILTER_PROJECTION: [],
                PATTERN: [],
                SEQUENCE: [],
                JOIN: []
            };
            // finalElementCount --> Number of elements that exist on the canvas at the time of saving the model
            this.finalElementCount = 0;

        };

        AppData.prototype.addStream = function (stream) {
            this.streamList.push(stream);
        };

        AppData.prototype.addTable = function (table) {
            this.tableList.push(table);
        };

        AppData.prototype.addWindow = function (window) {
            this.windowList.push(window);
        };

        AppData.prototype.addTrigger = function (trigger) {
            this.triggerList.push(trigger);
        };

        AppData.prototype.addAggregation = function (aggregation) {
            this.aggregationList.push(aggregation);
        };

        AppData.prototype.addFunction = function (functionObject) {
            this.functionList.push(functionObject);
        };

        AppData.prototype.addWindowFilterProjectionQuery = function (windowFilterProjectionQuery) {
            this.queryLists.WINDOW_FILTER_PROJECTION.push(windowFilterProjectionQuery);
        };

        AppData.prototype.addPatternQuery = function (patternQuery) {
            this.queryLists.PATTERN.push(patternQuery);
        };

        AppData.prototype.addSequenceQuery = function (sequenceQuery) {
            this.queryLists.SEQUENCE.push(sequenceQuery);
        };

        AppData.prototype.addJoinQuery = function (joinQuery) {
            this.queryLists.JOIN.push(joinQuery);
        };

        AppData.prototype.addPartition = function (partition) {
            this.partitionList.push(partition);
        };

        AppData.prototype.addSource = function (source) {
            this.sourceList.push(source);
        };

        AppData.prototype.addSink = function (sink) {
            this.sinkList.push(sink);
        };

        AppData.prototype.removeStream = function (streamId) {
            var isStreamDeleted = ElementUtils.prototype.removeElement(this.streamList, streamId);
            if(!isStreamDeleted) {
                isStreamDeleted = this.removeStreamSavedInsideAPartition(streamId);
            }
            return isStreamDeleted;
        };

        AppData.prototype.removeTable = function (tableId) {
            ElementUtils.prototype.removeElement(this.tableList, tableId);
        };

        AppData.prototype.removeWindow = function (windowId) {
            ElementUtils.prototype.removeElement(this.windowList, windowId);
        };

        AppData.prototype.removeTrigger = function (triggerId) {
            ElementUtils.prototype.removeElement(this.triggerList, triggerId);
        };

        AppData.prototype.removeAggregation = function (aggregationId) {
            ElementUtils.prototype.removeElement(this.aggregationList, aggregationId);
        };

        AppData.prototype.removeFunction = function (functionId) {
            ElementUtils.prototype.removeElement(this.functionList, functionId);
        };

        AppData.prototype.removeWindowFilterProjectionQuery = function (windowFilterProjectionQueryId) {
            var isQueryDeleted = ElementUtils.prototype
                .removeElement(this.queryLists.WINDOW_FILTER_PROJECTION, windowFilterProjectionQueryId);
            if(!isQueryDeleted) {
                isQueryDeleted =
                    this.removeQuerySavedInsideAPartition(windowFilterProjectionQueryId,
                        'WINDOW_FILTER_PROJECTION_QUERY');
            }
            return isQueryDeleted;
        };

        AppData.prototype.removePatternQuery = function (patternQueryId) {
            var isQueryDeleted = ElementUtils.prototype.removeElement(this.queryLists.PATTERN, patternQueryId);
            if(!isQueryDeleted) {
                isQueryDeleted = this.removeQuerySavedInsideAPartition(patternQueryId, 'PATTERN_QUERY');
            }
            return isQueryDeleted;
        };

        AppData.prototype.removeSequenceQuery = function (sequenceQueryId) {
            var isQueryDeleted = ElementUtils.prototype.removeElement(this.queryLists.SEQUENCE, sequenceQueryId);
            if(!isQueryDeleted) {
                isQueryDeleted = this.removeQuerySavedInsideAPartition(sequenceQueryId, 'SEQUENCE_QUERY');
            }
            return isQueryDeleted;
        };

        AppData.prototype.removeJoinQuery = function (joinQueryId) {
            var isQueryDeleted = ElementUtils.prototype.removeElement(this.queryLists.JOIN, joinQueryId);
            if(!isQueryDeleted) {
                isQueryDeleted = this.removeQuerySavedInsideAPartition(joinQueryId, 'JOIN_QUERY');
            }
            return isQueryDeleted;
        };

        AppData.prototype.removePartition = function (partitionId) {
            ElementUtils.prototype.removeElement(this.partitionList, partitionId);
        };

        AppData.prototype.removeSource = function (sourceId) {
            ElementUtils.prototype.removeElement(this.sourceList, sourceId);
        };

        AppData.prototype.removeSink = function (sinkId) {
            ElementUtils.prototype.removeElement(this.sinkList, sinkId);
        };

        AppData.prototype.setFinalElementCount = function (finalElementCount) {
            this.finalElementCount = finalElementCount;
        };

        AppData.prototype.getStream = function (streamId) {
            var returnedElement = ElementUtils.prototype.getElement(this.streamList, streamId);
            if (returnedElement === undefined) {
                returnedElement = this.getStreamSavedInsideAPartition(streamId);
            }
            return returnedElement;
        };

        AppData.prototype.getTable = function (tableId) {
            return ElementUtils.prototype.getElement(this.tableList, tableId);
        };

        AppData.prototype.getWindow = function (windowId) {
            return ElementUtils.prototype.getElement(this.windowList, windowId);
        };

        AppData.prototype.getTrigger = function (triggerId) {
            return ElementUtils.prototype.getElement(this.triggerList, triggerId);
        };

        AppData.prototype.getAggregation = function (aggregationId) {
            return ElementUtils.prototype.getElement(this.aggregationList, aggregationId);
        };

        AppData.prototype.getFunction = function (functionId) {
            return ElementUtils.prototype.getElement(this.functionList, functionId);
        };

        AppData.prototype.getWindowFilterProjectionQuery = function (windowFilterProjectionQueryId) {
            var returnedElement = ElementUtils.prototype.
            getElement(this.queryLists.WINDOW_FILTER_PROJECTION, windowFilterProjectionQueryId);
            if (returnedElement === undefined) {
                returnedElement =
                    this.getQuerySavedInsideAPartition(windowFilterProjectionQueryId, 'WINDOW_FILTER_PROJECTION_QUERY');
            }
            return returnedElement;
        };

        AppData.prototype.getPatternQuery = function (patternQueryId) {
            var returnedElement = ElementUtils.prototype.getElement(this.queryLists.PATTERN, patternQueryId);
            if (returnedElement === undefined) {
                returnedElement = this.getQuerySavedInsideAPartition(patternQueryId, 'PATTERN_QUERY');
            }
            return returnedElement;
        };

        AppData.prototype.getSequenceQuery = function (sequenceQueryId) {
            var returnedElement =  ElementUtils.prototype.getElement(this.queryLists.SEQUENCE, sequenceQueryId);
            if (returnedElement === undefined) {
                returnedElement = this.getQuerySavedInsideAPartition(sequenceQueryId, 'SEQUENCE_QUERY');
            }
            return returnedElement;
        };

        AppData.prototype.getJoinQuery = function (joinQueryId) {
            var returnedElement =  ElementUtils.prototype.getElement(this.queryLists.JOIN, joinQueryId);
            if (returnedElement === undefined) {
                returnedElement = this.getQuerySavedInsideAPartition(joinQueryId, 'JOIN_QUERY');
            }
            return returnedElement;
        };

        AppData.prototype.getPartition = function (partitionId) {
            return ElementUtils.prototype.getElement(this.partitionList, partitionId);
        };

        AppData.prototype.getSource = function (sourceId) {
            return ElementUtils.prototype.getElement(this.sourceList, sourceId);
        };

        AppData.prototype.getSink = function (sinkId) {
            return ElementUtils.prototype.getElement(this.sinkList, sinkId);
        };

        AppData.prototype.getStreamList = function () {
            return this.streamList;
        };

        AppData.prototype.getTableList = function () {
            return this.tableList;
        };

        AppData.prototype.getWindowList = function () {
            return this.windowList;
        };

        AppData.prototype.getTriggerList = function () {
            return this.triggerList;
        };

        AppData.prototype.getAggregationList = function () {
            return this.aggregationList;
        };

        AppData.prototype.getFunctionList = function () {
            return this.functionList;
        };

        AppData.prototype.getWindowFilterProjectionQueryList = function () {
            return this.queryLists.WINDOW_FILTER_PROJECTION;
        };

        AppData.prototype.getPatternQueryList = function () {
            return this.queryLists.PATTERN;
        };

        AppData.prototype.getSequenceQueryList = function () {
            return this.queryLists.SEQUENCE;
        };

        AppData.prototype.getJoinQueryList = function () {
            return this.queryLists.JOIN;
        };

        AppData.prototype.getPartitionList = function () {
            return this.partitionList;
        };

        AppData.prototype.getSourceList = function () {
            return this.sourceList;
        };

        AppData.prototype.getSinkList = function () {
            return this.sinkList;
        };

        AppData.prototype.getFinalElementCount = function () {
            return this.finalElementCount;
        };

        /**
         * @function Get the element by providing the element id
         * @param elementId id of the definition element
         * @param includeQueryTypes if true search in the queries as well
         * @param includeSourceAndSink if true search in the sinks and sources as well
         * @return requestedElement returns undefined if the requested element is not found
         */
        AppData.prototype.getDefinitionElementById = function (elementId, includeQueryTypes, includeSourceAndSink) {
            var self = this;
            var requestedElement = undefined;
            var streamList = self.streamList;
            var tableList = self.tableList;
            var windowList = self.windowList;
            var aggregationList = self.aggregationList;
            var functionList = self.functionList;
            var triggerList = self.triggerList;
            var windowFilterProjectionQueryList = self.queryLists.WINDOW_FILTER_PROJECTION;
            var patternQueryList = self.queryLists.PATTERN;
            var sequenceQueryList = self.queryLists.SEQUENCE;
            var joinQueryList = self.queryLists.JOIN;
            var sourceList = self.sourceList;
            var sinkList = self.sinkList;

            var lists = [streamList, tableList, windowList, aggregationList, functionList, triggerList];

            if (includeQueryTypes !== undefined && includeQueryTypes) {
                lists.push(windowFilterProjectionQueryList);
                lists.push(patternQueryList);
                lists.push(sequenceQueryList);
                lists.push(joinQueryList);
            }
            if (includeSourceAndSink !== undefined && includeSourceAndSink) {
                lists.push(sourceList);
                lists.push(sinkList);
            }

            _.forEach(lists, function (list) {
                _.forEach(list, function (element) {
                    if (element.getId() === elementId) {
                        var type = '';
                        if (list === streamList) {
                            type = 'STREAM';
                        } else if (list === tableList) {
                            type = 'TABLE';
                        } else if (list === windowList) {
                            type = 'WINDOW';
                        } else if (list === aggregationList) {
                            type = 'AGGREGATION';
                        } else if (list === functionList) {
                            type = 'FUNCTION';
                        } else if (list === triggerList) {
                            type = 'TRIGGER';
                        } else if (list === windowFilterProjectionQueryList) {
                            type = 'WINDOW_FILTER_PROJECTION_QUERY';
                        } else if (list === patternQueryList) {
                            type = 'PATTERN_QUERY';
                        } else if (list === sequenceQueryList) {
                            type = 'SEQUENCE_QUERY';
                        } else if (list === joinQueryList) {
                            type = 'JOIN_QUERY';
                        } else if (list === sourceList) {
                            type = 'SOURCE';
                        } else if (list === sinkList) {
                            type = 'SINK';
                        }
                        requestedElement = {
                            type: type,
                            element: element
                        };
                    }
                });
            });

            return requestedElement;
        };

        /**
         * @function Get the element by providing the element name
         * @param elementName name of the definition element
         * @param includeQueryTypes if true search in the queries as well
         * @return requestedElement returns undefined if the requested element is not found
         */
        AppData.prototype.getDefinitionElementByName = function (elementName, includeQueryTypes) {
            var self = this;
            var requestedElement = undefined;
            var streamList = self.streamList;
            var tableList = self.tableList;
            var windowList = self.windowList;
            var aggregationList = self.aggregationList;
            var functionList = self.functionList;
            var triggerList = self.triggerList;
            var windowFilterProjectionQueryList = self.queryLists.WINDOW_FILTER_PROJECTION;
            var patternQueryList = self.queryLists.PATTERN;
            var sequenceQueryList = self.queryLists.SEQUENCE;
            var joinQueryList = self.queryLists.JOIN;

            var listNames = [streamList, tableList, windowList, aggregationList, functionList, triggerList];

            if (includeQueryTypes !== undefined && includeQueryTypes) {
                listNames.push(windowFilterProjectionQueryList);
                listNames.push(patternQueryList);
                listNames.push(sequenceQueryList);
                listNames.push(joinQueryList);
            }

            _.forEach(listNames, function (list) {
                _.forEach(list, function (element) {
                    if (element.getName().toUpperCase() === elementName.toUpperCase()) {
                        var type = '';
                        if (list === streamList) {
                            type = 'STREAM';
                        } else if (list === tableList) {
                            type = 'TABLE';
                        } else if (list === windowList) {
                            type = 'WINDOW';
                        } else if (list === aggregationList) {
                            type = 'AGGREGATION';
                        } else if (list === functionList) {
                            type = 'FUNCTION';
                        } else if (list === triggerList) {
                            type = 'TRIGGER';
                        } else if (list === windowFilterProjectionQueryList) {
                            type = 'WINDOW_FILTER_PROJECTION_QUERY';
                        } else if (list === patternQueryList) {
                            type = 'PATTERN_QUERY';
                        } else if (list === sequenceQueryList) {
                            type = 'SEQUENCE_QUERY';
                        } else if (list === joinQueryList) {
                            type = 'JOIN_QUERY';
                        }
                        requestedElement = {
                            type: type,
                            element: element
                        };
                    }
                });
            });

            return requestedElement;
        };

        /**
         * @function Checks whether a given query is inside a partition and if yes it returns
         * @param queryId id of the query element
         * @param queryType type of the query
         * @return requestedElement returns undefined if the requested element is not found. Otherwise returns the
         * requestedElement
         */
        AppData.prototype.getQuerySavedInsideAPartition = function (queryId, queryType) {
            var self = this;
            var requestedElement = undefined;
            _.forEach(self.partitionList, function (partition) {
                if (requestedElement === undefined) {
                    if (queryType === 'WINDOW_FILTER_PROJECTION_QUERY') {
                        requestedElement = partition.getWindowFilterProjectionQuery(queryId);
                    } else if (queryType === 'PATTERN_QUERY') {
                        requestedElement = partition.getPatternQuery(queryId);
                    } else if (queryType === 'SEQUENCE_QUERY') {
                        requestedElement = partition.getSequenceQuery(queryId);
                    } else if (queryType === 'JOIN_QUERY') {
                        requestedElement = partition.getJoinQuery(queryId);
                    }
                }
            });
            return requestedElement;
        };

        /**
         * @function Checks whether a given stream is inside a partition and if yes it returns
         * @param streamId id of the query element
         * @return requestedElement returns undefined if the requested element is not found. Otherwise returns the
         * requestedElement
         */
        AppData.prototype.getStreamSavedInsideAPartition = function (streamId) {
            var self = this;
            var requestedElement = undefined;
            _.forEach(self.partitionList, function (partition) {
                if (requestedElement === undefined) {
                    requestedElement = partition.getStream(streamId);
                }
            });
            return requestedElement;
        };

        /**
         * @function Checks whether a given query is inside a partition and if yes removes it
         * @param queryId id of the query element
         * @param queryType type of the query
         * @return boolean returns false if the element is not found.
         */
        AppData.prototype.removeQuerySavedInsideAPartition = function (queryId, queryType) {
            var self = this;
            var isQueryDeleted = false;
            _.forEach(self.partitionList, function (partition) {
                if (!isQueryDeleted) {
                    if (queryType === 'WINDOW_FILTER_PROJECTION_QUERY') {
                        isQueryDeleted = partition.removeWindowFilterProjectionQuery(queryId);
                    } else if (queryType === 'PATTERN_QUERY') {
                        isQueryDeleted = partition.removePatternQuery(queryId);
                    } else if (queryType === 'SEQUENCE_QUERY') {
                        isQueryDeleted = partition.removeSequenceQuery(queryId);
                    } else if (queryType === 'JOIN_QUERY') {
                        isQueryDeleted = partition.removeJoinQuery(queryId);
                    }
                }
            });
            return isQueryDeleted;
        };

        /**
         * @function Checks whether a given stream is inside a partition and if yes removes it
         * @param streamId id of the stream element
         * @return boolean returns false if the element is not found.
         */
        AppData.prototype.removeStreamSavedInsideAPartition = function (streamId) {
            var self = this;
            var isStreamDeleted = false;
            _.forEach(self.partitionList, function (partition) {
                if (!isStreamDeleted) {
                    isStreamDeleted = partition.removeStream(streamId);
                }
            });
            return isStreamDeleted;
        };

        return AppData;
    });
<|endoftext|>


<commit_before>flattenArray.js
<commit_msg>add desc<commit_after>/**
 * Flatten a nested array using Helper Method of Recursion
 *
 * Input:   Array of Integers and Arrays
 * Output:  Array of Integers
 *
 * Example: flatten([1, [2, 3, [4]], 5, [[6]]]) => [1, 2, 3, 4, 5, 6]
 **/

function flatten(arr){

}
<|endoftext|>


<commit_before>define(['sprd/entity/DesignConfigurationBase', 'sprd/entity/Size', 'sprd/util/UnitUtil', 'sprd/model/Design', "sprd/entity/PrintTypeColor", "underscore",
        "sprd/model/PrintType", "sprd/util/ProductUtil", "js/core/List", "flow", "sprd/manager/IDesignConfigurationManager", "sprd/data/IImageUploadService"
        , "sprd/entity/BlobImage", "sprd/data/MaskService", "sprd/data/ImageService", "sprd/manager/ImageMeasurer"],
    function (DesignConfigurationBase, Size, UnitUtil, Design, PrintTypeColor, _, PrintType, ProductUtil, List, flow
        , IDesignConfigurationManager, IImageUploadService, BlobImage, MaskService, ImageService, ImageMeasurer) {

        return DesignConfigurationBase.inherit('sprd.model.DesignConfiguration', {
            defaults: {
                _dpi: "{printType.dpi}",

                _designCommission: "{design.price}",
                _allowScale: "{design.restrictions.allowScale}",

                afterEffect: null,
                processedDesign: null,
                processedImage: null,
                processedSize: null,
                innerRect: null
            },

            ctor: function () {
                this.callBase();

                this.bind('change:processedImage', this._setProcessedSize, this);
                this.bind('change:processedDesign', function () {
                    this._setOriginalDesignProperties()
                }, this);
                this.bind('change:rotation', function () {
                    this._debounceFunctionCall(this.setInnerRect, "innerRect", 800, this)
                }, this);
            },

            inject: {
                imageUploadService: IImageUploadService,
                maskService: MaskService,
                imageService: ImageService,
                context: "context"
            },

            type: "design",

            _commitPrintType: function (newPrintType, oldPrintType) {
                // print type changed -> convert colors

                if (!newPrintType) {
                    return;
                }

                var colors = [],
                    printColors = this.$.printColors;

                printColors.each(function (printColor) {
                    colors.push(newPrintType.getClosestPrintColor(printColor.color()));
                });

                if (newPrintType.$.id === PrintType.Mapping.SpecialFlex) {
                    // convert all colors to the first one
                    for (var i = 1; i < colors.length; i++) {
                        colors[i] = colors[0];
                    }
                }

                var original = this.get('originalPrintType');
                if (original && original !== oldPrintType) {
                    this.set('originalPrintType', null);
                }

                printColors.reset(colors);
                this.trigger('configurationChanged');
                this.trigger("priceChanged");
            },

            setInvertedColors: function () {
                var invertedColors = this.getInvertedDesignColors();
                this.$.printColors && this.$.printColors.reset(invertedColors);
            },

            getDesignColors: function (transformer) {
                var design = this.$.design,
                    printType = this.$.printType,
                    printColors = this.$.printColors;

                if (!design || !printType || !printColors || !design.isVectorDesign()) {
                    return;
                }

                var designColors = design ? design.$.colors : null;

                if (!designColors || !designColors.length) {
                    return;
                }

                var newPrintColors = [];
                designColors.each(function (designColor) {
                    var color = (designColor.$["default"] || designColor.$["origin"]).toRGB();
                    color = transformer instanceof Function ? transformer(color) : color;

                    var closestPrintColor = printType.getClosestPrintColor(color);
                    newPrintColors.push(closestPrintColor);
                });

                return newPrintColors;
            },

            getInvertedDesignColors: function () {
                return this.getDesignColors(function (color) {
                    return color.invert();
                })
            },

            _commitAfterEffect: function (afterEffect) {
                var self = this;

                if (!afterEffect) {
                    this.set('processedImage', null);
                } else {
                    this.$.maskService.applyAfterEffect(self.$.design, afterEffect, null, function (err, ctx) {
                        if (!err) {
                            self.setProcessedImage(ctx);
                        } else {
                            console.error(err);
                        }

                        afterEffect.callback && afterEffect.callback(err, ctx);
                    });
                }

                this.trigger('configurationChanged');
            },

            _validatePrintTypeSize: function (printType, width, height, scale) {
                var ret = this.callBase();
                var design = this.$.design;

                if (!printType || !scale || !_.isNumber(width) || !_.isNumber(height) || !design) {
                    return ret;
                }

                if (!design.isVectorDesign()) {
                    ret.dpiBound = scale.x > 1 || scale.y > 1;
                }

                return ret;
            },

            getMinScale: function () {
                var minScale = this.callBase() || Number.MIN_VALUE,
                    printType = this.$.printType;

                if (printType && !printType.isShrinkable()) {
                    minScale = Math.max(minScale, this.minimumScale());
                }

                return minScale;
            }.onChange("minimumScale()", "printType"),

            getMaxScale: function () {
                var maxScale = this.callBase(),
                    design = this.$.design;

                if (design && !design.isVectorDesign()) {
                    maxScale = Math.min(1, maxScale);
                }

                return maxScale;
            }.onChange("printType", "size()", "design"),

            _setProcessedSize: function () {
                var afterEffect = this.$.afterEffect;
                var design = this.$.design;

                if (afterEffect && this.$.processedImage) {
                    this.set('processedSize', this.$.maskService.getProcessedSize(afterEffect, design));
                } else {
                    this.set('processedSize', null);
                }

                this.trigger('sizeChanged');
            },

            applyAfterEffect: function (ctx) {
                this.setProcessedImage(ctx);
            },

            setProcessedImage: function (ctx) {
                var self = this;

                if (!self.$.design || !self.$.afterEffect) {
                    return;
                }

                var cacheId = [self.$.design.$.id, self.$.afterEffect.id()].join('#');
                self.synchronizeFunctionCall.call(self, function (cb) {
                    var img = self.$.maskService.trimAndExport(ctx, self.$.afterEffect, null);
                    cb(null, img);
                }, cacheId, function (err, result) {
                    self.set('processedImage', result);
                }, self);
            },

            getPrintColorsAsRGB: function () {
                var ret = [];

                if (this.$.design.$.colors.size() === this.$.printColors.size()) {
                    // go in the direction of the layers of the design
                    for (var i = 0; i < this.$.design.$.colors.$items.length; i++) {
                        var designColor = this.$.design.$.colors.$items[i];
                        var printColor = this.$.printColors.$items[i];
                        ret[designColor.$.layer] = printColor.color().toRGB().toHexString();
                    }
                }

                return ret;
            },

            setColor: function (layerIndex, color) {
                var printType = this.$.printType;

                if (!(color instanceof PrintTypeColor)) {
                    color = printType.getClosestPrintColor(color);
                }

                if (!printType.containsPrintTypeColor(color)) {
                    throw new Error("Color not contained in print type");
                }

                var printColors = this.$.printColors.$items;

                if (printColors[layerIndex] === color) {
                    return;
                }

                printColors.splice(layerIndex, 1, color);

                if (printType.$.id === PrintType.Mapping.SpecialFlex) {
                    // convert all other layers to the new color
                    for (var i = 0; i < printColors.length; i++) {
                        if (i !== layerIndex) {
                            printColors[i] = printColors[layerIndex];
                        }
                    }
                }

                this.$.printColors.reset(printColors);

                this.trigger('configurationChanged');
                this.trigger("priceChanged");
            },

            size: function () {
                return this.getSizeForPrintType(this.$.printType);
            }.onChange("_dpi", "design", "processedSize"),

            getSizeInPx: function (design, options) {
                options = options || {};
                design = design || this.$.design;
                return options.original ? design.$.size : this.$.processedSize || design.$.size;
            },

            getSizeForPrintType: function (printType, design, options) {
                options = options || {};
                design = design || this.$.design;
                printType = printType || this.$.printType;

                if (design && design.$.size && printType && printType.$.dpi) {
                    var dpi = printType.$.dpi;
                    var size = this.getSizeInPx(design, options);
                    return UnitUtil.convertSizeToMm(size, dpi);
                }

                return Size.empty;
            },

            isScalable: function () {
                return this.get("printType.isScalable()") && this.$._allowScale;
            }.onChange("printType", "_allowScale"),

            allowScale: function () {
                return this.$._allowScale;
            },

            getImageUrl: function () {
                var design = this.$.design;
                if (!design) {
                    return;
                }

                return this.$.processedImage || design.$.localImage || this.$.imageService.designImageFromCache(design.$.wtfMbsId, {
                    width: 100,
                    sameOrigin: true
                });
            },

            setInnerRect: function () {
                var self = this;
                this.getInnerRect(this.$.rotation, function (err, results) {
                    if (!err) {
                        self.set("innerRect", results.rect);
                    }
                });
            },

            getInnerRect: function (rotation, callback) {
                var url = this.getImageUrl();

                if (!url) {
                    callback && callback(new Error("Not able to get an image from current configuration."));
                    return;
                }

                flow()
                    .seq("image", function (cb) {
                        ImageMeasurer.toImage(url, cb)
                    })
                    .seq("rect", function () {
                        return ImageMeasurer.getRealDesignSize(this.vars.image, rotation);
                    })
                    .exec(callback)
            },

            price: function () {

                var usedPrintColors = [],
                    price = this.callBase();

                this.$.printColors.each(function (printColor) {
                    if (_.indexOf(usedPrintColors, printColor) === -1) {
                        usedPrintColors.push(printColor);
                    }
                });

                for (var i = 0; i < usedPrintColors.length; i++) {
                    if (usedPrintColors[i]) {
                        price.add((usedPrintColors[i]).get("price"));
                    }
                }

                price.add(this.get('_designCommission'));

                return price;

            }.on("priceChanged").onChange("_designCommission", "_printTypePrice"),

            getPossiblePrintTypes: function (appearance) {
                var ret = [],
                    printArea = this.$.printArea,
                    design = this.$.design;

                if (this.$context) {
                    appearance = appearance || this.$context.$contextModel.get('appearance');
                }

                if (printArea && appearance && design) {
                    ret = ProductUtil.getPossiblePrintTypesForDesignOnPrintArea(design, printArea, appearance);
                }

                return ret;
            }.onChange("printArea", "design"),

            _setAfterEffectProperties: function () {
                var afterEffect = this.get('afterEffect');
                var properties = this.get('properties');

                if (afterEffect) {
                    properties.afterEffect = _.extend(properties.afterEffect || {}, afterEffect.compose());
                    properties.type = 'afterEffect';
                } else if (properties.afterEffect || properties.type === "afterEffect") {
                    delete properties.afterEffect;
                    delete properties.type;
                }
            },

            _setOriginalDesignProperties: function (design) {
                var properties = this.get('properties'),
                    afterEffect = this.get('afterEffect');

                design = design || this.$.processedDesign;

                if (design && afterEffect) {
                    //Mask is already applied and processedImage uploaded
                    properties.afterEffect = properties.afterEffect || {};
                    properties.afterEffect.originalDesign = {
                        id: design.get('wtfMbsId'),
                        href: "/" + design.get("id")
                    };
                }
            },

            originalSize: function () {
                return this.getSizeForPrintType(this.$.printType, null, {original: true});
            },

            compose: function () {
                var processedDesign = this.get('processedDesign'),
                    originalDesign = this.get('design');

                if (processedDesign) {
                    this.set('design', processedDesign, {silent: true});
                }

                var ret = this.callBase();
                this._setAfterEffectProperties();
                this._setOriginalDesignProperties(originalDesign);
                ret.properties = this.$.properties;

                if (processedDesign && originalDesign) {
                    this.set('design', originalDesign);
                }

                return ret;
            },

            save: function (callback) {
                var self = this,
                    afterEffect = this.$.afterEffect;

                if (!afterEffect) {
                    callback && callback();
                } else {
                    flow()
                        .seq("design", function (cb) {
                            var afterEffect = self.$.afterEffect;
                            if (afterEffect) {
                                self.$.maskService.applyMask(afterEffect, self.$.design, self.$.context.$.id, cb);
                            }
                        })
                        .seq(function () {
                            if (this.vars.design) {
                                self.set('processedDesign', this.vars.design);
                            }
                        })
                        .exec(callback);
                }
            },

            parse: function (data) {
                data = this.callBase();

                if (data.designs) {
                    this.$$.design = data.designs[0];
                }

                data.designs = undefined;

                if (data.printArea) {
                    // remove printArea from payload since it is the wrong one
                    // it will be set within the initSchema methods
                    this.$$.printArea = data.printArea;
                    data.printArea = null;
                }

                if (data.content) {
                    this.$$.svg = data.content.svg;
                }

                return data;
            },

            saveTakesTime: function () {
                return this.get('afterEffect');
            },

            init: function (options, callback) {
                this.$.manager.initializeConfiguration(this, options, callback);
                this.setInnerRect();
            },

            isAllowedOnPrintArea: function (printArea) {
                return printArea && printArea.get("restrictions.designAllowed") == true;
            },

            getPossiblePrintTypesForPrintArea: function (printArea, appearance) {
                return ProductUtil.getPossiblePrintTypesForDesignOnPrintArea(this.$.design, printArea, appearance);
            },

            minimumScale: function () {
                return (this.get("design.restrictions.minimumScale") || 100 ) / 100;
            }.onChange("design.restrictions.minimumScale"),

            clone: function () {
                var afterEffect = this.$.afterEffect,
                    clone = this.callBase();

                if (afterEffect) {
                    var afterEffectClone = afterEffect.clone();
                    clone.set('afterEffect', afterEffectClone);
                }

                return clone;
            }
        });
    })
;<commit_msg>DEV-124863 trigger configurationChanged event after mask parameters changed. This will save trigger a new save to localStorage<commit_after>define(['sprd/entity/DesignConfigurationBase', 'sprd/entity/Size', 'sprd/util/UnitUtil', 'sprd/model/Design', "sprd/entity/PrintTypeColor", "underscore",
        "sprd/model/PrintType", "sprd/util/ProductUtil", "js/core/List", "flow", "sprd/manager/IDesignConfigurationManager", "sprd/data/IImageUploadService"
        , "sprd/entity/BlobImage", "sprd/data/MaskService", "sprd/data/ImageService", "sprd/manager/ImageMeasurer"],
    function (DesignConfigurationBase, Size, UnitUtil, Design, PrintTypeColor, _, PrintType, ProductUtil, List, flow
        , IDesignConfigurationManager, IImageUploadService, BlobImage, MaskService, ImageService, ImageMeasurer) {

        return DesignConfigurationBase.inherit('sprd.model.DesignConfiguration', {
            defaults: {
                _dpi: "{printType.dpi}",

                _designCommission: "{design.price}",
                _allowScale: "{design.restrictions.allowScale}",

                afterEffect: null,
                processedDesign: null,
                processedImage: null,
                processedSize: null,
                innerRect: null
            },

            ctor: function () {
                this.callBase();

                this.bind('change:processedImage', this._setProcessedSize, this);
                this.bind('afterEffect', "processingParametersChanged", function () {
                    this.trigger("configurationChanged");
                }, this);
                this.bind('change:processedDesign', function () {
                    this._setOriginalDesignProperties()
                }, this);
                this.bind('change:rotation', function () {
                    this._debounceFunctionCall(this.setInnerRect, "innerRect", 800, this)
                }, this);
            },

            inject: {
                imageUploadService: IImageUploadService,
                maskService: MaskService,
                imageService: ImageService,
                context: "context"
            },

            type: "design",

            _commitPrintType: function (newPrintType, oldPrintType) {
                // print type changed -> convert colors

                if (!newPrintType) {
                    return;
                }

                var colors = [],
                    printColors = this.$.printColors;

                printColors.each(function (printColor) {
                    colors.push(newPrintType.getClosestPrintColor(printColor.color()));
                });

                if (newPrintType.$.id === PrintType.Mapping.SpecialFlex) {
                    // convert all colors to the first one
                    for (var i = 1; i < colors.length; i++) {
                        colors[i] = colors[0];
                    }
                }

                var original = this.get('originalPrintType');
                if (original && original !== oldPrintType) {
                    this.set('originalPrintType', null);
                }

                printColors.reset(colors);
                this.trigger('configurationChanged');
                this.trigger("priceChanged");
            },

            setInvertedColors: function () {
                var invertedColors = this.getInvertedDesignColors();
                this.$.printColors && this.$.printColors.reset(invertedColors);
            },

            getDesignColors: function (transformer) {
                var design = this.$.design,
                    printType = this.$.printType,
                    printColors = this.$.printColors;

                if (!design || !printType || !printColors || !design.isVectorDesign()) {
                    return;
                }

                var designColors = design ? design.$.colors : null;

                if (!designColors || !designColors.length) {
                    return;
                }

                var newPrintColors = [];
                designColors.each(function (designColor) {
                    var color = (designColor.$["default"] || designColor.$["origin"]).toRGB();
                    color = transformer instanceof Function ? transformer(color) : color;

                    var closestPrintColor = printType.getClosestPrintColor(color);
                    newPrintColors.push(closestPrintColor);
                });

                return newPrintColors;
            },

            getInvertedDesignColors: function () {
                return this.getDesignColors(function (color) {
                    return color.invert();
                })
            },

            _commitAfterEffect: function (afterEffect) {
                var self = this;

                if (!afterEffect) {
                    this.set('processedImage', null);
                } else {
                    this.$.maskService.applyAfterEffect(self.$.design, afterEffect, null, function (err, ctx) {
                        if (!err) {
                            self.setProcessedImage(ctx);
                        } else {
                            console.error(err);
                        }

                        afterEffect.callback && afterEffect.callback(err, ctx);
                    });
                }

                this.trigger('configurationChanged');
            },

            _validatePrintTypeSize: function (printType, width, height, scale) {
                var ret = this.callBase();
                var design = this.$.design;

                if (!printType || !scale || !_.isNumber(width) || !_.isNumber(height) || !design) {
                    return ret;
                }

                if (!design.isVectorDesign()) {
                    ret.dpiBound = scale.x > 1 || scale.y > 1;
                }

                return ret;
            },

            getMinScale: function () {
                var minScale = this.callBase() || Number.MIN_VALUE,
                    printType = this.$.printType;

                if (printType && !printType.isShrinkable()) {
                    minScale = Math.max(minScale, this.minimumScale());
                }

                return minScale;
            }.onChange("minimumScale()", "printType"),

            getMaxScale: function () {
                var maxScale = this.callBase(),
                    design = this.$.design;

                if (design && !design.isVectorDesign()) {
                    maxScale = Math.min(1, maxScale);
                }

                return maxScale;
            }.onChange("printType", "size()", "design"),

            _setProcessedSize: function () {
                var afterEffect = this.$.afterEffect;
                var design = this.$.design;

                if (afterEffect && this.$.processedImage) {
                    this.set('processedSize', this.$.maskService.getProcessedSize(afterEffect, design));
                } else {
                    this.set('processedSize', null);
                }

                this.trigger('sizeChanged');
            },

            applyAfterEffect: function (ctx) {
                this.setProcessedImage(ctx);
            },

            setProcessedImage: function (ctx) {
                var self = this;

                if (!self.$.design || !self.$.afterEffect) {
                    return;
                }

                var cacheId = [self.$.design.$.id, self.$.afterEffect.id()].join('#');
                self.synchronizeFunctionCall.call(self, function (cb) {
                    var img = self.$.maskService.trimAndExport(ctx, self.$.afterEffect, null);
                    cb(null, img);
                }, cacheId, function (err, result) {
                    self.set('processedImage', result);
                }, self);
            },

            getPrintColorsAsRGB: function () {
                var ret = [];

                if (this.$.design.$.colors.size() === this.$.printColors.size()) {
                    // go in the direction of the layers of the design
                    for (var i = 0; i < this.$.design.$.colors.$items.length; i++) {
                        var designColor = this.$.design.$.colors.$items[i];
                        var printColor = this.$.printColors.$items[i];
                        ret[designColor.$.layer] = printColor.color().toRGB().toHexString();
                    }
                }

                return ret;
            },

            setColor: function (layerIndex, color) {
                var printType = this.$.printType;

                if (!(color instanceof PrintTypeColor)) {
                    color = printType.getClosestPrintColor(color);
                }

                if (!printType.containsPrintTypeColor(color)) {
                    throw new Error("Color not contained in print type");
                }

                var printColors = this.$.printColors.$items;

                if (printColors[layerIndex] === color) {
                    return;
                }

                printColors.splice(layerIndex, 1, color);

                if (printType.$.id === PrintType.Mapping.SpecialFlex) {
                    // convert all other layers to the new color
                    for (var i = 0; i < printColors.length; i++) {
                        if (i !== layerIndex) {
                            printColors[i] = printColors[layerIndex];
                        }
                    }
                }

                this.$.printColors.reset(printColors);

                this.trigger('configurationChanged');
                this.trigger("priceChanged");
            },

            size: function () {
                return this.getSizeForPrintType(this.$.printType);
            }.onChange("_dpi", "design", "processedSize"),

            getSizeInPx: function (design, options) {
                options = options || {};
                design = design || this.$.design;
                return options.original ? design.$.size : this.$.processedSize || design.$.size;
            },

            getSizeForPrintType: function (printType, design, options) {
                options = options || {};
                design = design || this.$.design;
                printType = printType || this.$.printType;

                if (design && design.$.size && printType && printType.$.dpi) {
                    var dpi = printType.$.dpi;
                    var size = this.getSizeInPx(design, options);
                    return UnitUtil.convertSizeToMm(size, dpi);
                }

                return Size.empty;
            },

            isScalable: function () {
                return this.get("printType.isScalable()") && this.$._allowScale;
            }.onChange("printType", "_allowScale"),

            allowScale: function () {
                return this.$._allowScale;
            },

            getImageUrl: function () {
                var design = this.$.design;
                if (!design) {
                    return;
                }

                return this.$.processedImage || design.$.localImage || this.$.imageService.designImageFromCache(design.$.wtfMbsId, {
                    width: 100,
                    sameOrigin: true
                });
            },

            setInnerRect: function () {
                var self = this;
                this.getInnerRect(this.$.rotation, function (err, results) {
                    if (!err) {
                        self.set("innerRect", results.rect);
                    }
                });
            },

            getInnerRect: function (rotation, callback) {
                var url = this.getImageUrl();

                if (!url) {
                    callback && callback(new Error("Not able to get an image from current configuration."));
                    return;
                }

                flow()
                    .seq("image", function (cb) {
                        ImageMeasurer.toImage(url, cb)
                    })
                    .seq("rect", function () {
                        return ImageMeasurer.getRealDesignSize(this.vars.image, rotation);
                    })
                    .exec(callback)
            },

            price: function () {

                var usedPrintColors = [],
                    price = this.callBase();

                this.$.printColors.each(function (printColor) {
                    if (_.indexOf(usedPrintColors, printColor) === -1) {
                        usedPrintColors.push(printColor);
                    }
                });

                for (var i = 0; i < usedPrintColors.length; i++) {
                    if (usedPrintColors[i]) {
                        price.add((usedPrintColors[i]).get("price"));
                    }
                }

                price.add(this.get('_designCommission'));

                return price;

            }.on("priceChanged").onChange("_designCommission", "_printTypePrice"),

            getPossiblePrintTypes: function (appearance) {
                var ret = [],
                    printArea = this.$.printArea,
                    design = this.$.design;

                if (this.$context) {
                    appearance = appearance || this.$context.$contextModel.get('appearance');
                }

                if (printArea && appearance && design) {
                    ret = ProductUtil.getPossiblePrintTypesForDesignOnPrintArea(design, printArea, appearance);
                }

                return ret;
            }.onChange("printArea", "design"),

            _setAfterEffectProperties: function () {
                var afterEffect = this.get('afterEffect');
                var properties = this.get('properties');

                if (afterEffect) {
                    properties.afterEffect = _.extend(properties.afterEffect || {}, afterEffect.compose());
                    properties.type = 'afterEffect';
                } else if (properties.afterEffect || properties.type === "afterEffect") {
                    delete properties.afterEffect;
                    delete properties.type;
                }
            },

            _setOriginalDesignProperties: function (design) {
                var properties = this.get('properties'),
                    afterEffect = this.get('afterEffect');

                design = design || this.$.processedDesign;

                if (design && afterEffect) {
                    //Mask is already applied and processedImage uploaded
                    properties.afterEffect = properties.afterEffect || {};
                    properties.afterEffect.originalDesign = {
                        id: design.get('wtfMbsId'),
                        href: "/" + design.get("id")
                    };
                }
            },

            originalSize: function () {
                return this.getSizeForPrintType(this.$.printType, null, {original: true});
            },

            compose: function () {
                var processedDesign = this.get('processedDesign'),
                    originalDesign = this.get('design');

                if (processedDesign) {
                    this.set('design', processedDesign, {silent: true});
                }

                var ret = this.callBase();
                this._setAfterEffectProperties();
                this._setOriginalDesignProperties(originalDesign);
                ret.properties = this.$.properties;

                if (processedDesign && originalDesign) {
                    this.set('design', originalDesign);
                }

                return ret;
            },

            save: function (callback) {
                var self = this,
                    afterEffect = this.$.afterEffect;

                if (!afterEffect) {
                    callback && callback();
                } else {
                    flow()
                        .seq("design", function (cb) {
                            var afterEffect = self.$.afterEffect;
                            if (afterEffect) {
                                self.$.maskService.applyMask(afterEffect, self.$.design, self.$.context.$.id, cb);
                            }
                        })
                        .seq(function () {
                            if (this.vars.design) {
                                self.set('processedDesign', this.vars.design);
                            }
                        })
                        .exec(callback);
                }
            },

            parse: function (data) {
                data = this.callBase();

                if (data.designs) {
                    this.$$.design = data.designs[0];
                }

                data.designs = undefined;

                if (data.printArea) {
                    // remove printArea from payload since it is the wrong one
                    // it will be set within the initSchema methods
                    this.$$.printArea = data.printArea;
                    data.printArea = null;
                }

                if (data.content) {
                    this.$$.svg = data.content.svg;
                }

                return data;
            },

            saveTakesTime: function () {
                return this.get('afterEffect');
            },

            init: function (options, callback) {
                this.$.manager.initializeConfiguration(this, options, callback);
                this.setInnerRect();
            },

            isAllowedOnPrintArea: function (printArea) {
                return printArea && printArea.get("restrictions.designAllowed") == true;
            },

            getPossiblePrintTypesForPrintArea: function (printArea, appearance) {
                return ProductUtil.getPossiblePrintTypesForDesignOnPrintArea(this.$.design, printArea, appearance);
            },

            minimumScale: function () {
                return (this.get("design.restrictions.minimumScale") || 100 ) / 100;
            }.onChange("design.restrictions.minimumScale"),

            clone: function () {
                var afterEffect = this.$.afterEffect,
                    clone = this.callBase();

                if (afterEffect) {
                    var afterEffectClone = afterEffect.clone();
                    clone.set('afterEffect', afterEffectClone);
                }

                return clone;
            }
        });
    })
;<|endoftext|>