<commit_before>/*
Controller for handling mongodb and the data model slide while providing CRUD'ish.
*/

'use strict';

const helper = require('./helper'),
    slideModel = require('../models/slide.js'),
    oid = require('mongodb').ObjectID;

module.exports = {
    get: function(identifier) {
        identifier = String(identifier);
        let idArray = identifier.split('-');
        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        //must parse the identifier to check if it is dash separated (get revision) or not (get the whole slide)
        .then((col) => col.findOne({
            _id: parseInt(idArray[0])
        })
        )
        .then((found) => {
            if(idArray.length === 1){
                return found;
            }
            else{
                //array index of revision is revision number minus 1
                let revision = found.revisions[parseInt(idArray[1])-1];
                if(typeof revision === 'undefined'){
                    return ;
                }
                else{
                    found.revisions = [revision];
                    return found;
                }
                // revision.id = identifier;
                // revision.kind = 'slide';
                // return revision;
            }
        }).catch((error) => {
            throw error;
        });

    },

    getAll: function(identifier) { //TODO Darya: is this function in use?
        return helper.connectToDatabase()
        .then((db) => db.collection('decks'))
        .then((col) => col.find({ content_id: String(oid(identifier)) }))//TODO use id TODO cast to String?
        .then((stream) => stream.sort({timestamp: -1}))
        .then((stream) => stream.toArray());
    },

    getSelected: function(identifiers) {
        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => col.find({ _id:  { $in : identifiers.selectedIDs.map(function(id) {
            return oid(id);
        })
    }}))
    .then((stream) => stream.sort({timestamp: -1}))
    .then((stream) => stream.toArray());
    },

    getAllFromCollection: function() {
        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => col.find())
        .then((stream) => stream.sort({timestamp: -1}))
        .then((stream) => stream.toArray());
    },

    insert: function(slide) {
        //TODO check for root and parent deck ids to be existant, otherwise create these
        return helper.connectToDatabase()
        .then((db) => helper.getNextIncrementationValueForCollection(db, 'slides'))
        .then((newId) => {
            return helper.connectToDatabase() //db connection have to be accessed again in order to work with more than one collection
            .then((db2) => db2.collection('slides'))
            .then((col) => {
                let valid = false;
                slide._id = newId;
                try {
                    const convertedSlide = convertToNewSlide(slide);
                    valid = slideModel(convertedSlide);
                    // console.log('validated slidemodel', valid);
                    if (!valid) {
                        return slideModel.errors;
                    }
                    //create thumbnail here

                    return col.insertOne(convertedSlide);
                } catch (e) {
                    console.log('validation failed', e);
                }
                return;
            }); //id is created and concatinated automatically
        });
    },

    copy: function(slide, slideRevision){
        return helper.connectToDatabase()
        .then((db) => helper.getNextIncrementationValueForCollection(db, 'slides'))
        .then((newId) => {
            return helper.connectToDatabase() //db connection have to be accessed again in order to work with more than one collection
            .then((db2) => db2.collection('slides'))
            .then((col) => {
                let valid = false;
                slide._id = newId;
                let revisionCopied = slide.revisions[slideRevision];
                let now = new Date();
                let timestamp = now.toISOString();
                let parentArray = slide.parent.split('-');
                if(parentArray.length > 1){
                    revisionCopied.parent = {'id': parseInt(parentArray[0]), 'revision': parseInt(parentArray[1])};
                }
                else{
                    revisionCopied.parent = slide.parent;
                }
                revisionCopied.comment = slide.comment;
                revisionCopied.id = 1;
                revisionCopied.timestamp = timestamp;
                slide.revisions = [revisionCopied];
                slide.timestamp = timestamp;
                // let contributors = slide.contributors;
                // let existingUserContributorIndex = findWithAttr(contributors, 'user', slide.user);
                // if(existingUserContributorIndex > -1)
                //     contributors[existingUserContributorIndex].count++;
                // else{
                //     contributors.push({'user': slide.user, 'count': 1});
                // }
                // slide.contributors = contributors;
                delete slide.parent;
                delete slide.comment;
                try {
                    return col.insertOne(slide);
                } catch (e) {
                    console.log('validation failed', e);
                }
                return;
            }); //id is created and concatinated automatically
        });
    },

    replace: function(id, slide) {
        let idArray = String(id).split('-');
        if(idArray.length > 1){
            id = idArray[0];
        }
        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => {
            return col.findOne({_id: parseInt(id)})
            .then((existingSlide) => {
                const maxRevisionId = existingSlide.revisions.reduce((prev, curr) => {
                    if (curr.id > prev)
                        return curr.id;

                    return prev;
                }, 1);
                let usageArray = existingSlide.revisions[idArray[1]-1].usage;
                //we should remove the usage of the previous revision in the root deck
                let previousUsageArray = JSON.parse(JSON.stringify(usageArray));
                if(slide.root_deck){
                    //console.log(slide.root_deck);

                    for(let i = 0; i < previousUsageArray.length; i++){
                        if(previousUsageArray[i].id === parseInt(slide.root_deck.split('-')[0]) && previousUsageArray[i].revision === parseInt(slide.root_deck.split('-')[1])){
                            previousUsageArray.splice(i,1);
                            break;
                        }
                    }
                }

                let valid = false;
                //should empty usage array and keep only the new root deck revision
                usageArray = [{'id':parseInt(slide.root_deck.split('-')[0]), 'revision': parseInt(slide.root_deck.split('-')[1])}];
                let slideWithNewRevision = convertSlideWithNewRevision(slide, parseInt(maxRevisionId)+1, usageArray);
                slideWithNewRevision.timestamp = existingSlide.timestamp;
                slideWithNewRevision.license = existingSlide.license;
                slideWithNewRevision.user = existingSlide.user;
                if(existingSlide.hasOwnProperty('contributors')){
                    let contributors = existingSlide.contributors;
                    let existingUserContributorIndex = findWithAttr(contributors, 'user', slide.user);
                    if(existingUserContributorIndex > -1)
                        contributors[existingUserContributorIndex].count++;
                    else{
                        contributors.push({'user': slide.user, 'count': 1});
                    }
                    slideWithNewRevision.contributors = contributors;
                }

                try {
                    valid = slideModel(slideWithNewRevision);
                    if (!valid) {
                        return slideModel.errors;
                    }
                    let new_revisions = existingSlide.revisions;
                    new_revisions[idArray[1]-1].usage = previousUsageArray;
                    new_revisions.push(slideWithNewRevision.revisions[0]);
                    slideWithNewRevision.revisions = new_revisions;
                    return col.findOneAndUpdate({
                        _id: parseInt(id)
                    //}, { $push: { revisions: slideWithNewRevision.revisions[0] } }, {new: true});
                    }, { $set: slideWithNewRevision }, {new: true});
                } catch (e) {
                    console.log('validation failed', e);
                }
                return;
            });
        });
    },

    replaceNoRevision: function(id, slide) {
        let idArray = id.split('-');

        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => {
            return col.findOne({_id: parseInt(idArray[0])})
            .then((existingSlide) => {

                let valid = false;
                const slideWithNewRevision = convertSlideWithNewRevision(slide, parseInt(idArray[1]));

                try {
                    valid = slideModel(slideWithNewRevision);

                    if (!valid) {
                        return slideModel.errors;
                    }
                    slideWithNewRevision.revisions[0].usage = existingSlide.revisions[idArray[1]-1].usage;
                    existingSlide.revisions[parseInt(idArray[1])-1] = slideWithNewRevision.revisions[0];
                    col.save(existingSlide);
                    return slideWithNewRevision;
                } catch (e) {
                    console.log('validation failed', e);
                }
                return;
            });
        });
    },

    saveDataSources: function(id, dataSources) {
        let idArray = id.split('-');

        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => {
            return col.findOne({_id: parseInt(idArray[0])})
            .then((existingSlide) => {
                try {
                    const revisionId = idArray[1];
                    let revision = (revisionId !== undefined) ? existingSlide.revisions.find((revision) => String(revision.id) === String(revisionId)) : undefined;
                    if (revision !== undefined) {
                        revision.dataSources = dataSources;
                    }

                    col.save(existingSlide);
                    return dataSources;
                } catch (e) {
                    console.log('saveDataSources failed', e);
                }
                return;
            });
        });
    },

    rename: function(slide_id, newName){
        let slideId = slide_id.split('-')[0];
        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => col.findOne({_id: parseInt(slideId)})
        .then((slide) => {
            if(slide.revisions.length > 1){
                slide.revisions[slide_id.split('-')[1]-1].title = newName;
            }
            else{
                slide.revisions[0].title = newName;
            }
            return col.findOneAndUpdate({_id: parseInt(slideId)}, slide);
        }));
    },

    revert: function(slide_id, slide){ //this can actually revert to past and future revisions
        //NOTE must add validation on id
        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => {
            col.findOne({_id: parseInt(slide_id)})
            .then((existingSlide) => {
                helper.connectToDatabase().collection('slides').findOne({_id: parseInt(existingSlide.deck)})
                .then((root_deck) => {
                    //console.log(root_deck);
                    for(let i = 0; i < root_deck.revisions.length; i++) {
                        if(root_deck.revisions[i].id === root_deck.active) {
                            for(let j = 0; j < root_deck.revisions[i].contentItems.length; j++) {
                                if(root_deck.revisions[i].contentItems[j].ref.id === String(slide_id)) {
                                    root_deck.revisions[i].contentItems[j].ref.revision = parseInt(slide.revision_id);
                                }
                                else continue;
                            }
                        }
                        else continue;
                    }
                    col.save(root_deck);
                });
            });
        });
    },

    updateUsage: function(slide, new_revision_id, root_deck){
        let idArray = slide.split('-');
        let rootDeckArray = root_deck.split('-');
        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => {
            return col.findOne({_id: parseInt(idArray[0])})
              .then((existingSlide) => {
                  //first remove usage of deck from old revision
                  let usageArray = existingSlide.revisions[parseInt(idArray[1])-1].usage;
                  for(let i = 0; i < usageArray.length; i++){
                      if(usageArray[i].id === parseInt(rootDeckArray[0]) && usageArray[i].revision === parseInt(rootDeckArray[1])){
                          usageArray.splice(i,1);
                          break;
                      }
                  }
                  //then update usage array of new/reverted revision
                  let contains = false;
                  for(let j = 0; j < existingSlide.revisions[parseInt(new_revision_id)-1].usage.length; j++){
                      if(existingSlide.revisions[parseInt(new_revision_id)-1].usage[j].id === parseInt(rootDeckArray[0]) && existingSlide.revisions[parseInt(new_revision_id)-1].usage[j].revision === parseInt(rootDeckArray[1])){
                          contains = true;
                          break;
                      }
                  }
                  if(!contains)
                      existingSlide.revisions[parseInt(new_revision_id)-1].usage.push({'id': parseInt(rootDeckArray[0]), 'revision': parseInt(rootDeckArray[1])});
                  //existingSlide.revisions[parseInt(new_revision_id)-1].usage.push({'id': parseInt(rootDeckArray[0]), 'revision': parseInt(rootDeckArray[1])});
                  col.save(existingSlide);
                  return existingSlide;
              });
        });
    },

    addToUsage: function(itemToAdd, root_deck_path){
        let itemId = itemToAdd.ref.id;
        let itemRevision = itemToAdd.ref.revision;
        let usageToPush = {id: parseInt(root_deck_path[0]), revision: parseInt(root_deck_path[1])};
        if(itemToAdd.kind === 'slide'){
            helper.connectToDatabase()
            .then((db) => db.collection('slides'))
            .then((col2) => {
                col2.findOneAndUpdate(
                    {_id: parseInt(itemId), 'revisions.id':itemRevision},
                    {$push: {'revisions.$.usage': usageToPush}}
                );
            });
        }
        else{
            helper.connectToDatabase()
            .then((db) => db.collection('decks'))
            .then((col2) => {
                col2.findOneAndUpdate(
                    {_id: parseInt(itemId), 'revisions.id':itemRevision},
                    {$push: {'revisions.$.usage': usageToPush}}
                );
            });
        }
    }
};

function convertToNewSlide(slide) {
    let now = new Date();
    //let root_deck = String(slide.root_deck.split('-')[0]); //we should put the deck revision in the usage as well...
    slide.user = parseInt(slide.user);
    let root_deck_array = slide.root_deck.split('-');
    let usageArray = [];
    usageArray.push({
        'id': parseInt(root_deck_array[0]),
        'revision': parseInt(root_deck_array[1])
    });
    if(slide.language === null){
        slide.language = 'en_EN';
    }
    let contributorsArray = [{'user': slide.user, 'count': 1}];
    const result = {
        _id: slide._id,
        user: slide.user,
        //kind: 'slide',
        //deck: String(slide.root_deck.split('-')[0]),
        timestamp: now.toISOString(),
        lastUpdate: now.toISOString(),
        language: slide.language,
        license: slide.license,
        contributors: contributorsArray,
        description: slide.description,
        revisions: [{
            id: 1,
            usage: usageArray,
            timestamp: now.toISOString(),
            user: slide.user,
            title: slide.title,
            content: slide.content,
            speakernotes: slide.speakernotes,
            parent: slide.parent_slide,
            tags: slide.tags,
            license: slide.license,
        }]
    };
    //console.log('from', slide, 'to', result);
    return result;
}

function convertSlideWithNewRevision(slide, newRevisionId, usageArray) {
    let now = new Date();
    slide.user = parseInt(slide.user);
    if(slide.language === null){
        slide.language = 'en_EN';
    }
    const result = {
        //user: slide.user,
        //deck: slide.root_deck,
        //timestamp: now.toISOString(),
        lastUpdate: now.toISOString(),
        language: slide.language,
        license: slide.license,
        revisions: [{
            id: newRevisionId,
            usage: usageArray,
            timestamp: now.toISOString(),
            user: slide.user,
            title: slide.title,
            content: slide.content,
            speakernotes: slide.speakernotes,
            tags: slide.tags,
            dataSources: slide.dataSources,
            license: slide.license
            //parent: slide.parent_slide
        }]
    };
    //console.log('from', slide, 'to', result);
    return result;
}

function findWithAttr(array, attr, value) {
    for(var i = 0; i < array.length; i++) {
        if(array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}
<commit_msg>[master] Fixed indention<commit_after>/*
Controller for handling mongodb and the data model slide while providing CRUD'ish.
*/

'use strict';

const helper = require('./helper'),
    slideModel = require('../models/slide.js'),
    oid = require('mongodb').ObjectID;

module.exports = {
    get: function(identifier) {
        identifier = String(identifier);
        let idArray = identifier.split('-');
        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        //must parse the identifier to check if it is dash separated (get revision) or not (get the whole slide)
        .then((col) => col.findOne({
            _id: parseInt(idArray[0])
        })
        )
        .then((found) => {
            if(idArray.length === 1){
                return found;
            }
            else{
                //array index of revision is revision number minus 1
                let revision = found.revisions[parseInt(idArray[1])-1];
                if(typeof revision === 'undefined'){
                    return ;
                }
                else{
                    found.revisions = [revision];
                    return found;
                }
                // revision.id = identifier;
                // revision.kind = 'slide';
                // return revision;
            }
        }).catch((error) => {
            throw error;
        });

    },

    getAll: function(identifier) { //TODO Darya: is this function in use?
        return helper.connectToDatabase()
        .then((db) => db.collection('decks'))
        .then((col) => col.find({ content_id: String(oid(identifier)) }))//TODO use id TODO cast to String?
        .then((stream) => stream.sort({timestamp: -1}))
        .then((stream) => stream.toArray());
    },

    getSelected: function(identifiers) {
        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => col.find({ _id:  { $in : identifiers.selectedIDs.map(function(id) {
            return oid(id);
        })
        }}))
    .then((stream) => stream.sort({timestamp: -1}))
    .then((stream) => stream.toArray());
    },

    getAllFromCollection: function() {
        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => col.find())
        .then((stream) => stream.sort({timestamp: -1}))
        .then((stream) => stream.toArray());
    },

    insert: function(slide) {
        //TODO check for root and parent deck ids to be existant, otherwise create these
        return helper.connectToDatabase()
        .then((db) => helper.getNextIncrementationValueForCollection(db, 'slides'))
        .then((newId) => {
            return helper.connectToDatabase() //db connection have to be accessed again in order to work with more than one collection
            .then((db2) => db2.collection('slides'))
            .then((col) => {
                let valid = false;
                slide._id = newId;
                try {
                    const convertedSlide = convertToNewSlide(slide);
                    valid = slideModel(convertedSlide);
                    // console.log('validated slidemodel', valid);
                    if (!valid) {
                        return slideModel.errors;
                    }
                    //create thumbnail here

                    return col.insertOne(convertedSlide);
                } catch (e) {
                    console.log('validation failed', e);
                }
                return;
            }); //id is created and concatinated automatically
        });
    },

    copy: function(slide, slideRevision){
        return helper.connectToDatabase()
        .then((db) => helper.getNextIncrementationValueForCollection(db, 'slides'))
        .then((newId) => {
            return helper.connectToDatabase() //db connection have to be accessed again in order to work with more than one collection
            .then((db2) => db2.collection('slides'))
            .then((col) => {
                let valid = false;
                slide._id = newId;
                let revisionCopied = slide.revisions[slideRevision];
                let now = new Date();
                let timestamp = now.toISOString();
                let parentArray = slide.parent.split('-');
                if(parentArray.length > 1){
                    revisionCopied.parent = {'id': parseInt(parentArray[0]), 'revision': parseInt(parentArray[1])};
                }
                else{
                    revisionCopied.parent = slide.parent;
                }
                revisionCopied.comment = slide.comment;
                revisionCopied.id = 1;
                revisionCopied.timestamp = timestamp;
                slide.revisions = [revisionCopied];
                slide.timestamp = timestamp;
                // let contributors = slide.contributors;
                // let existingUserContributorIndex = findWithAttr(contributors, 'user', slide.user);
                // if(existingUserContributorIndex > -1)
                //     contributors[existingUserContributorIndex].count++;
                // else{
                //     contributors.push({'user': slide.user, 'count': 1});
                // }
                // slide.contributors = contributors;
                delete slide.parent;
                delete slide.comment;
                try {
                    return col.insertOne(slide);
                } catch (e) {
                    console.log('validation failed', e);
                }
                return;
            }); //id is created and concatinated automatically
        });
    },

    replace: function(id, slide) {
        let idArray = String(id).split('-');
        if(idArray.length > 1){
            id = idArray[0];
        }
        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => {
            return col.findOne({_id: parseInt(id)})
            .then((existingSlide) => {
                const maxRevisionId = existingSlide.revisions.reduce((prev, curr) => {
                    if (curr.id > prev)
                        return curr.id;

                    return prev;
                }, 1);
                let usageArray = existingSlide.revisions[idArray[1]-1].usage;
                //we should remove the usage of the previous revision in the root deck
                let previousUsageArray = JSON.parse(JSON.stringify(usageArray));
                if(slide.root_deck){
                    //console.log(slide.root_deck);

                    for(let i = 0; i < previousUsageArray.length; i++){
                        if(previousUsageArray[i].id === parseInt(slide.root_deck.split('-')[0]) && previousUsageArray[i].revision === parseInt(slide.root_deck.split('-')[1])){
                            previousUsageArray.splice(i,1);
                            break;
                        }
                    }
                }

                let valid = false;
                //should empty usage array and keep only the new root deck revision
                usageArray = [{'id':parseInt(slide.root_deck.split('-')[0]), 'revision': parseInt(slide.root_deck.split('-')[1])}];
                let slideWithNewRevision = convertSlideWithNewRevision(slide, parseInt(maxRevisionId)+1, usageArray);
                slideWithNewRevision.timestamp = existingSlide.timestamp;
                slideWithNewRevision.license = existingSlide.license;
                slideWithNewRevision.user = existingSlide.user;
                if(existingSlide.hasOwnProperty('contributors')){
                    let contributors = existingSlide.contributors;
                    let existingUserContributorIndex = findWithAttr(contributors, 'user', slide.user);
                    if(existingUserContributorIndex > -1)
                        contributors[existingUserContributorIndex].count++;
                    else{
                        contributors.push({'user': slide.user, 'count': 1});
                    }
                    slideWithNewRevision.contributors = contributors;
                }

                try {
                    valid = slideModel(slideWithNewRevision);
                    if (!valid) {
                        return slideModel.errors;
                    }
                    let new_revisions = existingSlide.revisions;
                    new_revisions[idArray[1]-1].usage = previousUsageArray;
                    new_revisions.push(slideWithNewRevision.revisions[0]);
                    slideWithNewRevision.revisions = new_revisions;
                    return col.findOneAndUpdate({
                        _id: parseInt(id)
                    //}, { $push: { revisions: slideWithNewRevision.revisions[0] } }, {new: true});
                    }, { $set: slideWithNewRevision }, {new: true});
                } catch (e) {
                    console.log('validation failed', e);
                }
                return;
            });
        });
    },

    replaceNoRevision: function(id, slide) {
        let idArray = id.split('-');

        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => {
            return col.findOne({_id: parseInt(idArray[0])})
            .then((existingSlide) => {

                let valid = false;
                const slideWithNewRevision = convertSlideWithNewRevision(slide, parseInt(idArray[1]));

                try {
                    valid = slideModel(slideWithNewRevision);

                    if (!valid) {
                        return slideModel.errors;
                    }
                    slideWithNewRevision.revisions[0].usage = existingSlide.revisions[idArray[1]-1].usage;
                    existingSlide.revisions[parseInt(idArray[1])-1] = slideWithNewRevision.revisions[0];
                    col.save(existingSlide);
                    return slideWithNewRevision;
                } catch (e) {
                    console.log('validation failed', e);
                }
                return;
            });
        });
    },

    saveDataSources: function(id, dataSources) {
        let idArray = id.split('-');

        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => {
            return col.findOne({_id: parseInt(idArray[0])})
            .then((existingSlide) => {
                try {
                    const revisionId = idArray[1];
                    let revision = (revisionId !== undefined) ? existingSlide.revisions.find((revision) => String(revision.id) === String(revisionId)) : undefined;
                    if (revision !== undefined) {
                        revision.dataSources = dataSources;
                    }

                    col.save(existingSlide);
                    return dataSources;
                } catch (e) {
                    console.log('saveDataSources failed', e);
                }
                return;
            });
        });
    },

    rename: function(slide_id, newName){
        let slideId = slide_id.split('-')[0];
        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => col.findOne({_id: parseInt(slideId)})
        .then((slide) => {
            if(slide.revisions.length > 1){
                slide.revisions[slide_id.split('-')[1]-1].title = newName;
            }
            else{
                slide.revisions[0].title = newName;
            }
            return col.findOneAndUpdate({_id: parseInt(slideId)}, slide);
        }));
    },

    revert: function(slide_id, slide){ //this can actually revert to past and future revisions
        //NOTE must add validation on id
        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => {
            col.findOne({_id: parseInt(slide_id)})
            .then((existingSlide) => {
                helper.connectToDatabase().collection('slides').findOne({_id: parseInt(existingSlide.deck)})
                .then((root_deck) => {
                    //console.log(root_deck);
                    for(let i = 0; i < root_deck.revisions.length; i++) {
                        if(root_deck.revisions[i].id === root_deck.active) {
                            for(let j = 0; j < root_deck.revisions[i].contentItems.length; j++) {
                                if(root_deck.revisions[i].contentItems[j].ref.id === String(slide_id)) {
                                    root_deck.revisions[i].contentItems[j].ref.revision = parseInt(slide.revision_id);
                                }
                                else continue;
                            }
                        }
                        else continue;
                    }
                    col.save(root_deck);
                });
            });
        });
    },

    updateUsage: function(slide, new_revision_id, root_deck){
        let idArray = slide.split('-');
        let rootDeckArray = root_deck.split('-');
        return helper.connectToDatabase()
        .then((db) => db.collection('slides'))
        .then((col) => {
            return col.findOne({_id: parseInt(idArray[0])})
              .then((existingSlide) => {
                  //first remove usage of deck from old revision
                  let usageArray = existingSlide.revisions[parseInt(idArray[1])-1].usage;
                  for(let i = 0; i < usageArray.length; i++){
                      if(usageArray[i].id === parseInt(rootDeckArray[0]) && usageArray[i].revision === parseInt(rootDeckArray[1])){
                          usageArray.splice(i,1);
                          break;
                      }
                  }
                  //then update usage array of new/reverted revision
                  let contains = false;
                  for(let j = 0; j < existingSlide.revisions[parseInt(new_revision_id)-1].usage.length; j++){
                      if(existingSlide.revisions[parseInt(new_revision_id)-1].usage[j].id === parseInt(rootDeckArray[0]) && existingSlide.revisions[parseInt(new_revision_id)-1].usage[j].revision === parseInt(rootDeckArray[1])){
                          contains = true;
                          break;
                      }
                  }
                  if(!contains)
                      existingSlide.revisions[parseInt(new_revision_id)-1].usage.push({'id': parseInt(rootDeckArray[0]), 'revision': parseInt(rootDeckArray[1])});
                  //existingSlide.revisions[parseInt(new_revision_id)-1].usage.push({'id': parseInt(rootDeckArray[0]), 'revision': parseInt(rootDeckArray[1])});
                  col.save(existingSlide);
                  return existingSlide;
              });
        });
    },

    addToUsage: function(itemToAdd, root_deck_path){
        let itemId = itemToAdd.ref.id;
        let itemRevision = itemToAdd.ref.revision;
        let usageToPush = {id: parseInt(root_deck_path[0]), revision: parseInt(root_deck_path[1])};
        if(itemToAdd.kind === 'slide'){
            helper.connectToDatabase()
            .then((db) => db.collection('slides'))
            .then((col2) => {
                col2.findOneAndUpdate(
                    {_id: parseInt(itemId), 'revisions.id':itemRevision},
                    {$push: {'revisions.$.usage': usageToPush}}
                );
            });
        }
        else{
            helper.connectToDatabase()
            .then((db) => db.collection('decks'))
            .then((col2) => {
                col2.findOneAndUpdate(
                    {_id: parseInt(itemId), 'revisions.id':itemRevision},
                    {$push: {'revisions.$.usage': usageToPush}}
                );
            });
        }
    }
};

function convertToNewSlide(slide) {
    let now = new Date();
    //let root_deck = String(slide.root_deck.split('-')[0]); //we should put the deck revision in the usage as well...
    slide.user = parseInt(slide.user);
    let root_deck_array = slide.root_deck.split('-');
    let usageArray = [];
    usageArray.push({
        'id': parseInt(root_deck_array[0]),
        'revision': parseInt(root_deck_array[1])
    });
    if(slide.language === null){
        slide.language = 'en_EN';
    }
    let contributorsArray = [{'user': slide.user, 'count': 1}];
    const result = {
        _id: slide._id,
        user: slide.user,
        //kind: 'slide',
        //deck: String(slide.root_deck.split('-')[0]),
        timestamp: now.toISOString(),
        lastUpdate: now.toISOString(),
        language: slide.language,
        license: slide.license,
        contributors: contributorsArray,
        description: slide.description,
        revisions: [{
            id: 1,
            usage: usageArray,
            timestamp: now.toISOString(),
            user: slide.user,
            title: slide.title,
            content: slide.content,
            speakernotes: slide.speakernotes,
            parent: slide.parent_slide,
            tags: slide.tags,
            license: slide.license,
        }]
    };
    //console.log('from', slide, 'to', result);
    return result;
}

function convertSlideWithNewRevision(slide, newRevisionId, usageArray) {
    let now = new Date();
    slide.user = parseInt(slide.user);
    if(slide.language === null){
        slide.language = 'en_EN';
    }
    const result = {
        //user: slide.user,
        //deck: slide.root_deck,
        //timestamp: now.toISOString(),
        lastUpdate: now.toISOString(),
        language: slide.language,
        license: slide.license,
        revisions: [{
            id: newRevisionId,
            usage: usageArray,
            timestamp: now.toISOString(),
            user: slide.user,
            title: slide.title,
            content: slide.content,
            speakernotes: slide.speakernotes,
            tags: slide.tags,
            dataSources: slide.dataSources,
            license: slide.license
            //parent: slide.parent_slide
        }]
    };
    //console.log('from', slide, 'to', result);
    return result;
}

function findWithAttr(array, attr, value) {
    for(var i = 0; i < array.length; i++) {
        if(array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}
<|endoftext|>


<commit_before>/**
 * Created by Pavel on 02.12.2016.
 */

function prepareNoteFormAndFillNotes(place_name) {
    //TODO zmenit na podminku jestli ma ten user place u sebe nebo ne .. takhle to bere i mista co pridali ostatni
    checkIfPlaceAlreadyExistsInDb(place_name, function (place_id) {
        if(place_id != null && place_id != undefined){
            document.getElementById('addNote').addEventListener("click", function () {
                var addNoteDiv = document.getElementById("addNoteDiv");
                addNoteDiv.style = "display: block; text-align: center;";
                addNoteDiv.innerHTML =
                    "Název" +
                    "<input id='note_name' type='text' class='form-control'>
" +
                    "Obsah" +
                    "<input id='note_content' type='text' class='form-control'>
" +
                    "<button id='add-note-submit-btn'>Přidat</button>";
                document.getElementById("add-note-submit-btn").addEventListener("click", function () {
                    var noteObj = {name: document.getElementById("note_name").value, content: document.getElementById("note_content").value}
                    console.log(noteObj);
                    addNoteToPlace(place_id, noteObj);
                    //clear form
                    document.getElementById("note_name").innerText = "";
                    document.getElementById("note_content").innerText = "";
                })
            })
            getAndShowNotesForPlace(place_id);
        }
    });
}

function addNoteToPlace(place_id, note) {
    var data = "name="+note.name+"&content="+note.content;
    var user_id = localStorage.getItem("id");
    var url = "https://ivebeenthereapi-matyapav.rhcloud.com/notesForPlace/"+place_id+"/user/"+user_id;
    makeCorsRequest("POST", url, data, function (response) {
        console.log(response);
        getAndShowNotesForPlace(place_id);//refresh notes
    })
}

function removeNote(note_id, place_id) {
    if(confirm("Do you really want to delete this note?")) {
        var user_id = localStorage.getItem("id");
        var url = "https://ivebeenthereapi-matyapav.rhcloud.com/notes/" + note_id + "/user/" + user_id;
        makeCorsRequest("DELETE", url, null, function (response) {
            console.log(response);
            getAndShowNotesForPlace(place_id);//refresh notes
        })
    }
}

function getAndShowNotesForPlace(place_id) {
    var user_id = localStorage.getItem("id");
    var url = "https://ivebeenthereapi-matyapav.rhcloud.com/notesForPlace/"+place_id+"/user/"+user_id;
    makeCorsRequest("GET", url, null, function (response) {
        console.log(response);
        var notes = JSON.parse(response);
        var notesElement = document.getElementById('myNotes');
        notesElement.innerHTML = "";
        var index = 0;
        notes.forEach(function (note) {
            notesElement.innerHTML+=""+note.name+" "+note.content+" x
"
            document.getElementById("deleteNote"+index).addEventListener("click", function () {
                removeNote(note._id, place_id);
            });
            index++;
        })
    })
}
<commit_msg>styles<commit_after>/**
 * Created by Pavel on 02.12.2016.
 */

function prepareNoteFormAndFillNotes(place_name) {
    //TODO zmenit na podminku jestli ma ten user place u sebe nebo ne .. takhle to bere i mista co pridali ostatni
    checkIfPlaceAlreadyExistsInDb(place_name, function (place_id) {
        if(place_id != null && place_id != undefined){
            document.getElementById('addNote').addEventListener("click", function () {
                var addNoteDiv = document.getElementById("addNoteDiv");
                addNoteDiv.style = "display: block; text-align: center;";
                addNoteDiv.innerHTML =
                    "Název" +
                    "<input id='note_name' type='text' class='form-control'>
" +
                    "Obsah" +
                    "<textarea  rows='5' id='note_content' class='form-control'>
" +
                    "<button id='add-note-submit-btn'>Přidat</button>";
                document.getElementById("add-note-submit-btn").addEventListener("click", function () {
                    var noteObj = {name: document.getElementById("note_name").value, content: document.getElementById("note_content").value}
                    console.log(noteObj);
                    addNoteToPlace(place_id, noteObj);
                    //clear form
                    document.getElementById("note_name").innerText = "";
                    document.getElementById("note_content").innerText = "";
                })
            })
            getAndShowNotesForPlace(place_id);
        }
    });
}

function addNoteToPlace(place_id, note) {
    var data = "name="+note.name+"&content="+note.content;
    var user_id = localStorage.getItem("id");
    var url = "https://ivebeenthereapi-matyapav.rhcloud.com/notesForPlace/"+place_id+"/user/"+user_id;
    makeCorsRequest("POST", url, data, function (response) {
        console.log(response);
        getAndShowNotesForPlace(place_id);//refresh notes
    })
}

function removeNote(note_id, place_id) {
    if(confirm("Do you really want to delete this note?")) {
        var user_id = localStorage.getItem("id");
        var url = "https://ivebeenthereapi-matyapav.rhcloud.com/notes/" + note_id + "/user/" + user_id;
        makeCorsRequest("DELETE", url, null, function (response) {
            console.log(response);
            getAndShowNotesForPlace(place_id);//refresh notes
        })
    }
}

function getAndShowNotesForPlace(place_id) {
    var user_id = localStorage.getItem("id");
    var url = "https://ivebeenthereapi-matyapav.rhcloud.com/notesForPlace/"+place_id+"/user/"+user_id;
    makeCorsRequest("GET", url, null, function (response) {
        console.log(response);
        var notes = JSON.parse(response);
        var notesElement = document.getElementById('myNotes');
        notesElement.innerHTML = "";
        var index = 0;
        notes.forEach(function (note) {
            notesElement.innerHTML+=""+note.name+" "+note.content+" x
"
            document.getElementById("deleteNote"+index).addEventListener("click", function () {
                removeNote(note._id, place_id);
            });
            index++;
        })
    })
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux'
import { findDOMNode } from 'react-dom';
import ItemTypes from './ItemTypes';
import { DragSource, DropTarget } from 'react-dnd';
import DropdownList from 'react-widgets/lib/DropdownList'
import Combobox from 'react-widgets/lib/Combobox'
import Multiselect from 'react-widgets/lib/Multiselect'

const sequenceSource = {
  beginDrag(props) {
    return {
      id: props.id,
      index: props.index
    };
  }
}

const sequenceTarget = {
  hover(props, monitor, component) {
    const dragIndex = monitor.getItem().index;
    const hoverIndex = props.index;

    // Don't replace items with themselves
    if (dragIndex === hoverIndex) {
      return;
    }

    // Determine rectangle on screen
    const hoverBoundingRect = findDOMNode(component).getBoundingClientRect();

    // Get vertical middle
    const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;

    // Determine mouse position
    const clientOffset = monitor.getClientOffset();

    // Get pixels to the top
    const hoverClientY = clientOffset.y - hoverBoundingRect.top;

    // Only perform the move when the mouse has crossed half of the items height
    // When dragging downwards, only move when the cursor is below 50%
    // When dragging upwards, only move when the cursor is above 50%

    // Dragging downwards
    if (dragIndex < hoverIndex && clientOffset.y < hoverBoundingRect.top) {
      return;
    }

    // Dragging upwards
    if (dragIndex > hoverIndex && clientOffset.y > hoverBoundingRect.bottom) {
      return;
    }

    // Time to actually perform the action
    props.moveSequence(dragIndex, hoverIndex);

    // Note: we're mutating the monitor item here!
    // Generally it's better to avoid mutations,
    // but it's good here for the sake of performance
    // to avoid expensive index searches.
    monitor.getItem().index = hoverIndex;
  }
}

function collectDragSource(connect, monitor) {
  return {
    connectDragSource: connect.dragSource(),
    connectDragPreview: connect.dragPreview(),
    isDragging: monitor.isDragging()
  }
}

function collectDropTarget(connect, monitor) {
  return {
    connectDropTarget: connect.dropTarget(),
    isDraggingTarget: monitor.isOver()
  }
}

const renderSequenceOrder = field => (

    {field.input.value}

)

var MultiselectGrouping = React.createClass({
  render() {
    const item = this.props.item
    var typeIcon;
    var sectionName;

    if (item == "user") {
        typeIcon =
        sectionName = { ItemTypes.USER_DIRECTORY }
    } else if ( item == 'endpoint' ) {
      typeIcon =
      sectionName = { ItemTypes.EXTERNAL_NUMBER }
    } else if ( item == 'extension' ) {
      typeIcon =
      sectionName = { ItemTypes.EXTENSION }
    };

    return (

      {typeIcon} {sectionName}

    );

  }
})

var MultiselectTargetStyle = React.createClass({
  render() {
    var target = this.props.item
    var typeIcon;
    if (target.type == "user") {
        typeIcon =
    } else if ( target.type == 'endpoint' ) {
      typeIcon =
    } else if ( target.type == 'extension' ) {
      typeIcon =
    };

    return (

        { typeIcon} {target.target }
      );
  }
})

class renderSequenceForm extends Component {
  render() {
    const { formType,
            input,
            cmdData,
            data,
            alterSequence,
            changeHandler,
            blurHandler,
            addTarget,
            index,
            hoverOverInput,
            hoverOutOfInput,
            overInput
          } = this.props

    if (formType == 'Combobox') {
      return (

      		<Combobox
      		  value       = { input.value.command }
            textField   = 'command'
            valueField  = 'id'
      		  data        = { data }
            suggest     = { true }
      		  onChange    = {
							    event => {
								    changeHandler('routingForm', input.name+'.command', event);
								    alterSequence(index, event, input.value, 'command');
							    }
						}
            onMouseEnter = { event => ( hoverOverInput(event) ) }
            onMouseLeave = { event => ( hoverOutOfInput(event) ) }

      		/>

      )
    }

    else if (formType == 'Input') {
			return (

      		<input
     			  type        = "text"
      			value       = { input.value.cmdData }
            placeholder = { input.value.command.data_template }
      			onChange    = {
						      event => {
      			        changeHandler('routingForm', input.name+'.cmdData', event.target.value);
      			      }
      			}
      			onBlur      = {
      			      event => {
      			        blurHandler('routingForm', input.name+'.cmdData', event.target.value);
      			        alterSequence(index, event.target.value, input.value, 'cmdData');
      			      }
      			}
            onMouseEnter = { event => ( hoverOverInput(event) ) }
            onMouseLeave = { event => ( hoverOutOfInput(event) ) }
      		/>

			)
		}

    else if (formType == 'Multiselect') {
      return (

				  <Multiselect
            textField       = 'target'
            valueField      = 'id'
            data            = { data }
            value    = { cmdData || [] }
            placeholder     = { input.value.command.data_template }
						tagComponent    = { MultiselectTargetStyle }
						itemComponent   = { MultiselectTargetStyle }
            groupBy         = 'type'
            groupComponent  = { MultiselectGrouping }
            onCreate        = {(
              new_target => addTarget(index, new_target, input.value)
            )}
            onChange        = {
              event => {
              	changeHandler('routingForm', input.name+'.cmdData', event);
              	alterSequence(index, event, input.value, 'cmdData');
              }
            }
            onMouseEnter = { event => ( hoverOverInput(event) ) }
            onMouseLeave = { event => ( hoverOutOfInput(event) ) }

				  />

      )
		}
		else {
			return (

					Error: No FormType defined

			)
		}
  }
}

const Close = ({ removeSequence, index, sequenceId  }) => (
        <button
          type        = "button"
          className   = "close"
          aria-label  = "Close"
          onClick     = { removeSequence.bind(null, index, sequenceId) } >
          ×
        </button>
)

@DropTarget(ItemTypes.SEQUENCE, sequenceTarget,collectDropTarget)
@DragSource(ItemTypes.SEQUENCE, sequenceSource, collectDragSource)
class Sequence extends Component {
  static propTypes = {
    connectDragSource: PropTypes.func.isRequired,
    connectDropTarget: PropTypes.func.isRequired,
    index: PropTypes.number.isRequired,
    isDragging: PropTypes.bool.isRequired,
    sequenceField: PropTypes.any.isRequired,
    moveSequence: PropTypes.func.isRequired,
    removeSequence: PropTypes.func.isRequired,
    addTarget: PropTypes.func.isRequired,
  };

    render() {
    const { sequenceField,
						alterSequence,
            removeSequence,
						addTarget,
            index,
            isDragging,
            isDraggingTarget,
            connectDragSource,
            connectDropTarget,
            sequenceFormArray,
            availableExtensions,
            applicationCatalog,
            changeHandler,
            blurHandler,
            hoverOverInput,
            hoverOutOfInput,
            overInput
          } = this.props

    let sequenceContent = (

          <Field
            name={`${sequenceField}.sequence`}
            type="text"
            component={renderSequenceOrder}
          />

            <Field
		  				formType        = 'Combobox'
              name            = { `${sequenceField}` }
              component       = { renderSequenceForm }
              data            = { applicationCatalog }
		  				alterSequence   = { alterSequence }
              changeHandler   = { changeHandler }
              index           = { index }
              hoverOverInput  = { hoverOverInput }
              hoverOutOfInput = { hoverOutOfInput }
              overInput       = { overInput }
            />

            {sequenceFormArray && sequenceFormArray.command.command != "bridge" &&
              <Field
		  					formType      = 'Input'
                name          = { `${sequenceField}` }
                component     = { renderSequenceForm }
                data          = { sequenceFormArray.cmdData }
		  			  	alterSequence = { alterSequence }
                changeHandler = { changeHandler }
                blurHandler   = { blurHandler }
                index         = { index }
                hoverOverInput  = { hoverOverInput }
                hoverOutOfInput = { hoverOutOfInput }
                overInput       = { overInput }

              />
            }

            {sequenceFormArray && sequenceFormArray.command.command == "bridge" &&
            <Field
		  				formType      = 'Multiselect'
              name          = { `${sequenceField}` }
              component     = { renderSequenceForm }
              data          = { availableExtensions }
              cmdData       = { sequenceFormArray.cmdData }
		  				alterSequence = { alterSequence }
              changeHandler = { changeHandler }
              addTarget     = { addTarget }
              index         = { index }
              hoverOverInput  = { hoverOverInput }
              hoverOutOfInput = { hoverOutOfInput }
              overInput       = { overInput }
            />
            }

          {sequenceFormArray &&
          <Close
            index           = { index }
            sequenceId      = { sequenceFormArray.sequence_id }
            removeSequence  = { removeSequence }
          />
          }

    )

    // Don't allow dragging if mouse is over an input-field
    if ( !overInput )
      {
        return connectDragSource( connectDropTarget (
          sequenceContent
        ));
      }
    else
      {
        return sequenceContent
      }
  }
}

export default Sequence;
<commit_msg>code layout cleanup<commit_after>import React, { Component, PropTypes } from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux'
import { findDOMNode } from 'react-dom';
import ItemTypes from './ItemTypes';
import { DragSource, DropTarget } from 'react-dnd';
import DropdownList from 'react-widgets/lib/DropdownList'
import Combobox from 'react-widgets/lib/Combobox'
import Multiselect from 'react-widgets/lib/Multiselect'

const sequenceSource = {
  beginDrag(props) {
    return {
      id: props.id,
      index: props.index
    };
  }
}

const sequenceTarget = {
  hover(props, monitor, component) {
    const dragIndex = monitor.getItem().index;
    const hoverIndex = props.index;

    // Don't replace items with themselves
    if (dragIndex === hoverIndex) {
      return;
    }

    // Determine rectangle on screen
    const hoverBoundingRect = findDOMNode(component).getBoundingClientRect();

    // Get vertical middle
    const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;

    // Determine mouse position
    const clientOffset = monitor.getClientOffset();

    // Get pixels to the top
    const hoverClientY = clientOffset.y - hoverBoundingRect.top;

    // Only perform the move when the mouse has crossed half of the items height
    // When dragging downwards, only move when the cursor is below 50%
    // When dragging upwards, only move when the cursor is above 50%

    // Dragging downwards
    if (dragIndex < hoverIndex && clientOffset.y < hoverBoundingRect.top) {
      return;
    }

    // Dragging upwards
    if (dragIndex > hoverIndex && clientOffset.y > hoverBoundingRect.bottom) {
      return;
    }

    // Time to actually perform the action
    props.moveSequence(dragIndex, hoverIndex);

    // Note: we're mutating the monitor item here!
    // Generally it's better to avoid mutations,
    // but it's good here for the sake of performance
    // to avoid expensive index searches.
    monitor.getItem().index = hoverIndex;
  }
}

function collectDragSource(connect, monitor) {
  return {
    connectDragSource: connect.dragSource(),
    connectDragPreview: connect.dragPreview(),
    isDragging: monitor.isDragging()
  }
}

function collectDropTarget(connect, monitor) {
  return {
    connectDropTarget: connect.dropTarget(),
    isDraggingTarget: monitor.isOver()
  }
}

const renderSequenceOrder = field => (

    {field.input.value}

)

var MultiselectGrouping = React.createClass({
  render() {
    const item = this.props.item
    var typeIcon;
    var sectionName;

    if (item == "user") {
        typeIcon =
        sectionName = { ItemTypes.USER_DIRECTORY }
    } else if ( item == 'endpoint' ) {
      typeIcon =
      sectionName = { ItemTypes.EXTERNAL_NUMBER }
    } else if ( item == 'extension' ) {
      typeIcon =
      sectionName = { ItemTypes.EXTENSION }
    };

    return (

      {typeIcon} {sectionName}

    );

  }
})

var MultiselectTargetStyle = React.createClass({
  render() {
    var target = this.props.item
    var typeIcon;
    if (target.type == "user") {
        typeIcon =
    } else if ( target.type == 'endpoint' ) {
      typeIcon =
    } else if ( target.type == 'extension' ) {
      typeIcon =
    };

    return (

        { typeIcon} {target.target }
      );
  }
})

class renderSequenceForm extends Component {
  render() {
    const { formType,
            input,
            cmdData,
            data,
            alterSequence,
            changeHandler,
            blurHandler,
            addTarget,
            index,
            hoverOverInput,
            hoverOutOfInput,
            overInput
          } = this.props

    if (formType == 'Input') {
			return (

      		<input
     			  type        = "text"
      			value       = { input.value.cmdData }
            placeholder = { input.value.command.data_template }
      			onChange    = {
						      event => {
      			        changeHandler('routingForm', input.name+'.cmdData', event.target.value);
      			      }
      			}
      			onBlur      = {
      			      event => {
      			        blurHandler('routingForm', input.name+'.cmdData', event.target.value);
      			        alterSequence(index, event.target.value, input.value, 'cmdData');
      			      }
      			}
            onMouseEnter = { event => ( hoverOverInput(event) ) }
            onMouseLeave = { event => ( hoverOutOfInput(event) ) }
      		/>

			)
		}

    else if (formType == 'Combobox') {
      return (

      		<Combobox
      		  value       = { input.value.command }
            textField   = 'command'
            valueField  = 'id'
      		  data        = { data }
            suggest     = { true }
      		  onChange    = {
							    event => {
								    changeHandler('routingForm', input.name+'.command', event);
								    alterSequence(index, event, input.value, 'command');
							    }
						}
            onMouseEnter = { event => ( hoverOverInput(event) ) }
            onMouseLeave = { event => ( hoverOutOfInput(event) ) }

      		/>

      )
    }

    else if (formType == 'Multiselect') {
      return (

				  <Multiselect
            textField       = 'target'
            valueField      = 'id'
            data            = { data }
            value           = { cmdData || [] }
            placeholder     = { input.value.command.data_template }
						tagComponent    = { MultiselectTargetStyle }
						itemComponent   = { MultiselectTargetStyle }
            groupBy         = 'type'
            groupComponent  = { MultiselectGrouping }
            onCreate        = {(
              new_target => addTarget(index, new_target, input.value)
            )}
            onChange        = {
              event => {
              	changeHandler('routingForm', input.name+'.cmdData', event);
              	alterSequence(index, event, input.value, 'cmdData');
              }
            }
            onMouseEnter = { event => ( hoverOverInput(event) ) }
            onMouseLeave = { event => ( hoverOutOfInput(event) ) }

				  />

      )
		}
		else {
			return (

					Error: No FormType defined

			)
		}
  }
}

const Close = ({ removeSequence, index, sequenceId  }) => (
        <button
          type        = "button"
          className   = "close"
          aria-label  = "Close"
          onClick     = { removeSequence.bind(null, index, sequenceId) } >
          ×
        </button>
)

@DropTarget(ItemTypes.SEQUENCE, sequenceTarget,collectDropTarget)
@DragSource(ItemTypes.SEQUENCE, sequenceSource, collectDragSource)
class Sequence extends Component {
  static propTypes = {
    connectDragSource: PropTypes.func.isRequired,
    connectDropTarget: PropTypes.func.isRequired,
    index: PropTypes.number.isRequired,
    isDragging: PropTypes.bool.isRequired,
    sequenceField: PropTypes.any.isRequired,
    moveSequence: PropTypes.func.isRequired,
    removeSequence: PropTypes.func.isRequired,
    addTarget: PropTypes.func.isRequired,
  };

    render() {
    const { sequenceField,
						alterSequence,
            removeSequence,
						addTarget,
            index,
            isDragging,
            isDraggingTarget,
            connectDragSource,
            connectDropTarget,
            sequenceFormArray,
            availableExtensions,
            applicationCatalog,
            changeHandler,
            blurHandler,
            hoverOverInput,
            hoverOutOfInput,
            overInput
          } = this.props

    let sequenceContent = (

          <Field
            name={`${sequenceField}.sequence`}
            type="text"
            component={renderSequenceOrder}
          />

          <Field
		  			formType        = 'Combobox'
            name            = { `${sequenceField}` }
            component       = { renderSequenceForm }
            data            = { applicationCatalog }
		  			alterSequence   = { alterSequence }
            changeHandler   = { changeHandler }
            index           = { index }
            hoverOverInput  = { hoverOverInput }
            hoverOutOfInput = { hoverOutOfInput }
            overInput       = { overInput }
          />

          {sequenceFormArray.command.command != "bridge" &&
            <Field
		  				formType      = 'Input'
              name          = { `${sequenceField}` }
              component     = { renderSequenceForm }
              data          = { sequenceFormArray.cmdData }
		  		  	alterSequence = { alterSequence }
              changeHandler = { changeHandler }
              blurHandler   = { blurHandler }
              index         = { index }
              hoverOverInput  = { hoverOverInput }
              hoverOutOfInput = { hoverOutOfInput }
              overInput       = { overInput }

            />
          }

          {sequenceFormArray.command.command == "bridge" &&
          <Field
		  			formType      = 'Multiselect'
            name          = { `${sequenceField}` }
            component     = { renderSequenceForm }
            data          = { availableExtensions }
            cmdData       = { sequenceFormArray.cmdData }
		  			alterSequence = { alterSequence }
            changeHandler = { changeHandler }
            addTarget     = { addTarget }
            index         = { index }
            hoverOverInput  = { hoverOverInput }
            hoverOutOfInput = { hoverOutOfInput }
            overInput       = { overInput }
          />
          }

          <Close
            index           = { index }
            sequenceId      = { sequenceFormArray.sequence_id }
            removeSequence  = { removeSequence }
          />

    )

    // Don't allow dragging if mouse is over an input-field
    if ( !overInput )
      {
        return connectDragSource( connectDropTarget (
          sequenceContent
        ));
      }
    else
      {
        return sequenceContent
      }
  }
}

export default Sequence;
<|endoftext|>


<commit_before>#!/usr/bin/env node

var path = require('path'),
    fs = require('fs'),
    Getopt = require('node-getopt'),
    U = require('uglify-js');

function check(node, markers) {
    if (!(node instanceof U.AST_Call)) {
        return false;
    }

    for (var i = 0; i < markers.length; i++) {
        var m = markers[i].split('.');
        if (node.start.value === m[0] &&
            node.expression.end.value === m[m.length - 1]) {
            return true;
        }
    }

    return false;
}

function extract(fn, markers) {
    var ast, code, results, visitor, walker;
    results = [];

    visitor = function(node, descend) {
        if (!check(node, markers)) {
            return;
        }

        var a = node.args;
        var entry = ["#: " + fn + ":" + node.start.line];

        if (a.length > 1 && typeof a[1].value === 'string') {
            entry.push([a[0].value, a[1].value]);
        } else {
            entry.push(a[0].value);
        }

        results.push(entry);
    };

    code = fs.readFileSync(fn).toString();
    try {
        ast = U.parse(code);
    } catch (e) {
        console.log(fn);
        throw e;
    }

    walker = new U.TreeWalker(visitor);
    ast.walk(walker);
    return results;
}

function walk(filepath, callback) {
    return fs.stat(filepath, function(err, stat) {
        if (err) {
            return callback(err);
        }

        if (stat.isDirectory()) {
            return fs.readdir(filepath, function(err, files) {
                return files.forEach(function(fn) {
                    return walk(path.join(filepath, fn), callback);
                });
            });
        } else if (path.extname(filepath) === '.js') {
            return callback(null, filepath);
        }
    });
}

function format(s, ctx) {
    return s.replace(/\{([^\}]+)\}/g, function(match, k) {
        return ctx[k];
    });
}

function e(s) {
    return JSON.stringify(s);
}

function format_msgid(data) {
    data = extract_comments(data)
    if (typeof data.m === 'string') {
        return format(data.c + 'msgid {msg}\nmsgstr ""\n',
                           {msg: e(data.m)});
    }
    return format(data.c + 'msgid {one}\nmsgid_plural {two}\n' +
                  'msgstr[0] ""\nmsgstr[1] ""\n',
                  {one: e(data.m[0]), two: e(data.m[1])});
}

function extract_comments(msg) {
    var comments = []

    msg = [].concat(msg).map(function(m) {
        return m.replace(/\{([^\}]+)\}/g, function(_, k) {
            k = k.split('#').map(eval.call, ''.trim)
            if (k[1]) {
                comments.push('#. ' + k[0] + ' - ' + k[1] + '\n')
            }
            return '{' + k[0] + '}'
        })
    })

    return {
        c: comments.join(''),
        m: msg[1] ? msg : msg[0]
    }
}

var uniq = [],
    toString$ = ({}).toString;

function process(fn, markers) {
    if (!markers || !markers.length) {
        markers = ['__'];
    }

    // print minimal sufficient header
    console.log(
        'msgid ""\nmsgstr ""\n"Content-Type: text/plain; charset=UTF-8\\n"\n');

    return walk(fn, function(err, fn) {
        var messages = extract(fn, markers), msg, comment, _key;

        for (var i = 0; i < messages.length; i++) {
            comment = messages[i][0];
            msg = messages[i][1];

            // hard stop if we received something strange
            if (msg === undefined) {
                console.log("ERROR: something went wrong in " + fn);
                process.exit(1);
            }

            // output message string
            _key = toString$.call(msg).slice(8,-1)==="Array"?msg.join("|"):msg
            if (!~uniq.indexOf(_key)) {
                uniq.push(_key);
                console.log(comment);
                console.log(format_msgid(msg));
            }
        }
    });
}

function run() {
    var getopt = new Getopt([
        ['m', 'marker=ARG+',
         'function name identifying a translatable string (default: __)'],
        ['h', 'help', 'display this help']
    ]).bindHelp();

    var opt = getopt.parseSystem();

    if (!opt.argv.length) {
        return getopt.showHelp();
    }

    process(opt.argv[0], opt.options.marker);
}

run();
<commit_msg>code formatted<commit_after>#!/usr/bin/env node

var path = require('path'),
    fs = require('fs'),
    Getopt = require('node-getopt'),
    U = require('uglify-js');

function check(node, markers) {
    if (!(node instanceof U.AST_Call)) {
        return false;
    }

    for (var i = 0; i < markers.length; i++) {
        var m = markers[i].split('.');
        if (node.start.value === m[0] &&
            node.expression.end.value === m[m.length - 1]) {
            return true;
        }
    }

    return false;
}

function extract(fn, markers) {
    var ast, code, results, visitor, walker;
    results = [];

    visitor = function(node, descend) {
        if (!check(node, markers)) {
            return;
        }

        var a = node.args;
        var entry = ["#: " + fn + ":" + node.start.line];

        if (a.length > 1 && typeof a[1].value === 'string') {
            entry.push([a[0].value, a[1].value]);
        } else {
            entry.push(a[0].value);
        }

        results.push(entry);
    };

    code = fs.readFileSync(fn).toString();
    try {
        ast = U.parse(code);
    } catch (e) {
        console.log(fn);
        throw e;
    }

    walker = new U.TreeWalker(visitor);
    ast.walk(walker);
    return results;
}

function walk(filepath, callback) {
    return fs.stat(filepath, function(err, stat) {
        if (err) {
            return callback(err);
        }

        if (stat.isDirectory()) {
            return fs.readdir(filepath, function(err, files) {
                return files.forEach(function(fn) {
                    return walk(path.join(filepath, fn), callback);
                });
            });
        } else if (path.extname(filepath) === '.js') {
            return callback(null, filepath);
        }
    });
}

function format(s, ctx) {
    return s.replace(/\{([^\}]+)\}/g, function(match, k) {
        return ctx[k];
    });
}

function e(s) {
    return JSON.stringify(s);
}

function format_msgid(data) {
    data = extract_comments(data)
    if (typeof data.m === 'string') {
        return format(data.c + 'msgid {msg}\nmsgstr ""\n',
                           {msg: e(data.m)});
    }
    return format(data.c + 'msgid {one}\nmsgid_plural {two}\n' +
                  'msgstr[0] ""\nmsgstr[1] ""\n',
                  {one: e(data.m[0]), two: e(data.m[1])});
}

function extract_comments(msg) {
    var comments = []

    msg = [].concat(msg).map(function(m) {
        return m.replace(/\{([^\}]+)\}/g, function(_, k) {
            k = k.split('#').map(eval.call, ''.trim)
            if (k[1]) {
                comments.push('#. ' + k[0] + ' - ' + k[1] + '\n')
            }
            return '{' + k[0] + '}'
        })
    })

    return {
        c: comments.join(''),
        m: msg[1] ? msg : msg[0]
    }
}

var uniq = [],
    toString$ = ({}).toString;

function process(fn, markers) {
    if (!markers || !markers.length) {
        markers = ['__'];
    }

    // print minimal sufficient header
    console.log(
        'msgid ""\nmsgstr ""\n"Content-Type: text/plain; charset=UTF-8\\n"\n');

    return walk(fn, function(err, fn) {
        var messages = extract(fn, markers), msg, comment, _key;

        for (var i = 0; i < messages.length; i++) {
            comment = messages[i][0];
            msg = messages[i][1];

            // hard stop if we received something strange
            if (msg === undefined) {
                console.log("ERROR: something went wrong in " + fn);
                process.exit(1);
            }

            // output message string
            _key = toString$.call(msg).slice(8,-1) === "Array" ? msg.join("|") : msg;
            if (!~uniq.indexOf(_key)) {
                uniq.push(_key);
                console.log(comment);
                console.log(format_msgid(msg));
            }
        }
    });
}

function run() {
    var getopt = new Getopt([
        ['m', 'marker=ARG+',
         'function name identifying a translatable string (default: __)'],
        ['h', 'help', 'display this help']
    ]).bindHelp();

    var opt = getopt.parseSystem();

    if (!opt.argv.length) {
        return getopt.showHelp();
    }

    process(opt.argv[0], opt.options.marker);
}

run();
<|endoftext|>


<commit_before>'use strict';

/**
 * Requirements
 * @ignore
 */
const Command = require('./Command.js').Command;
const Server = require('../server/Server.js').Server;
const Context = require('../application/Context.js').Context;
const Communication = require('../application/Communication.js').Communication;
const CliLogger = require('../cli/CliLogger.js').CliLogger;
const ModelSynchronizer = require('../watch/ModelSynchronizer.js').ModelSynchronizer;
const ErrorHandler = require('../error/ErrorHandler.js').ErrorHandler;
const co = require('co');

/**
 * @memberOf command
 */
class ServerCommand extends Command
{
    /**
     * @param {application.Context} context
     * @param {Object} options
     */
    constructor(context, options)
    {
        super(context);

        this._name = 'server';
        this._options = options || {};
        this._server = false;
    }

    /**
     * @inheritDoc
     */
    static get injections()
    {
        return { 'parameters': [Context, 'command/ServerCommand.options'] };
    }

    /**
     * @inheritDocs
     */
    static get className()
    {
        return 'command/ServerCommand';
    }

    /**
     * @type {server.Server}
     */
    get server()
    {
        return this._server;
    }

    /**
     * @type {Object}
     */
    get options()
    {
        return this._options;
    }

    /**
     * @inheritDocs
     */
    get help()
    {
        const help =
        {
            name: this._name,
            description: 'Provides the development server',
            actions:
            [
                {
                    name: 'start',
                    options: [],
                    description: 'Start the server'
                }
            ]
        };
        return help;
    }

    /**
     * @returns {Promise<server.Server>}
     */
    start(parameters)
    {
        const scope = this;
        const promise = co(function*()
        {
            if (!scope.server)
            {
                const logger = scope.createLogger('command.server');

                // Start ipc communication
                logger.info('Starting IPC server');
                const com = scope.context.di.create(Communication);
                com.events.on('find-server', () =>
                {
                    if (scope.server && scope.server.baseUrl)
                    {
                        com.send('found-server', scope.server.baseUrl);
                    }
                });
                com.serve();

                // prepare routes
                const configure = logger.section('Configuring routes');
                const routes = [];
                if (Array.isArray(scope.options.routes))
                {
                    for (const route of scope.options.routes)
                    {
                        const work = logger.work('Configuring route <' + route.type.className + '>');
                        const type = route.type;
                        const mappings = new Map();
                        for (const key in route)
                        {
                            if (key !== 'type')
                            {
                                mappings.set(type.className + '.' + key, route[key]);
                            }
                        }
                        mappings.set(CliLogger, logger);
                        const routeInstance = scope.context.di.create(type, mappings);
                        if (!routeInstance)
                        {
                            throw new Error('Could not get instance of ' + type.className);
                        }
                        routes.push(routeInstance);
                        logger.end(work);
                    }
                }
                logger.end(configure);

                // create server
                const start = logger.section('Starting server');
                try
                {
                    scope._server = new Server(logger, routes, scope.options);
                }
                catch(error)
                {
                    ErrorHandler.error(scope, error);
                    logger.end(start, true);
                }

                // start server
                yield scope.server.start();

                // start synchronizer
                const modelSynchronizer = scope.context.di.create(ModelSynchronizer);
                yield modelSynchronizer.start();

                // Done
                logger.end(start);
            }

            return scope.server;
        }).catch(ErrorHandler.handler(scope));
        return promise;
    }

    /**
     * @inheritDocs
     * @returns {Promise<Server>}
     */
    dispatch(action, parameters)
    {
        return this.start();
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.ServerCommand = ServerCommand;
<commit_msg>feat(command.ServerCommand): listen to ipc linter broadcasts and update entitites<commit_after>'use strict';

/**
 * Requirements
 * @ignore
 */
const Command = require('./Command.js').Command;
const Server = require('../server/Server.js').Server;
const Context = require('../application/Context.js').Context;
const Communication = require('../application/Communication.js').Communication;
const CliLogger = require('../cli/CliLogger.js').CliLogger;
const ModelSynchronizer = require('../watch/ModelSynchronizer.js').ModelSynchronizer;
const EntitiesRepository = require('../model/entity/EntitiesRepository.js').EntitiesRepository;
const ErrorHandler = require('../error/ErrorHandler.js').ErrorHandler;
const co = require('co');

/**
 * @memberOf command
 */
class ServerCommand extends Command
{
    /**
     * @param {application.Context} context
     * @param {Object} options
     */
    constructor(context, options)
    {
        super(context);

        this._name = 'server';
        this._options = options || {};
        this._server = false;
    }

    /**
     * @inheritDoc
     */
    static get injections()
    {
        return { 'parameters': [Context, 'command/ServerCommand.options'] };
    }

    /**
     * @inheritDocs
     */
    static get className()
    {
        return 'command/ServerCommand';
    }

    /**
     * @type {server.Server}
     */
    get server()
    {
        return this._server;
    }

    /**
     * @type {Object}
     */
    get options()
    {
        return this._options;
    }

    /**
     * @inheritDocs
     */
    get help()
    {
        const help =
        {
            name: this._name,
            description: 'Provides the development server',
            actions:
            [
                {
                    name: 'start',
                    options: [],
                    description: 'Start the server'
                }
            ]
        };
        return help;
    }

    /**
     *
     */
    importLinterResults(lintResults)
    {
        if (!lintResults)
        {
            return;
        }
        const scope = this;
        co(function *()
        {
            const entityRepository = scope.context.di.create(EntitiesRepository);
            for (const lintResult of lintResults)
            {
                const entityAspect = yield entityRepository.getById(lintResult.entity);
                if (entityAspect)
                {
                    lintResult.site = entityAspect.id.site;
                    entityAspect.entity.lintResults.import(lintResult);
                }
            }
        });
    }

    /**
     * @returns {Promise<server.Server>}
     */
    start(parameters)
    {
        const scope = this;
        const promise = co(function*()
        {
            if (!scope.server)
            {
                const logger = scope.createLogger('command.server');

                // Start ipc communication
                logger.info('Starting IPC server');
                const com = scope.context.di.create(Communication);
                com.events.on('find-server', () =>
                {
                    if (scope.server && scope.server.baseUrl)
                    {
                        com.send('found-server', scope.server.baseUrl);
                    }
                });
                com.events.on('lint-results', (data) =>
                {
                    scope.importLinterResults(data);
                });
                com.serve();

                // prepare routes
                const configure = logger.section('Configuring routes');
                const routes = [];
                if (Array.isArray(scope.options.routes))
                {
                    for (const route of scope.options.routes)
                    {
                        const work = logger.work('Configuring route <' + route.type.className + '>');
                        const type = route.type;
                        const mappings = new Map();
                        for (const key in route)
                        {
                            if (key !== 'type')
                            {
                                mappings.set(type.className + '.' + key, route[key]);
                            }
                        }
                        mappings.set(CliLogger, logger);
                        const routeInstance = scope.context.di.create(type, mappings);
                        if (!routeInstance)
                        {
                            throw new Error('Could not get instance of ' + type.className);
                        }
                        routes.push(routeInstance);
                        logger.end(work);
                    }
                }
                logger.end(configure);

                // create server
                const start = logger.section('Starting server');
                try
                {
                    scope._server = new Server(logger, routes, scope.options);
                }
                catch(error)
                {
                    ErrorHandler.error(scope, error);
                    logger.end(start, true);
                }

                // start server
                yield scope.server.start();

                // start synchronizer
                const modelSynchronizer = scope.context.di.create(ModelSynchronizer);
                yield modelSynchronizer.start();

                // Done
                logger.end(start);
            }

            return scope.server;
        }).catch(ErrorHandler.handler(scope));
        return promise;
    }

    /**
     * @inheritDocs
     * @returns {Promise<Server>}
     */
    dispatch(action, parameters)
    {
        return this.start();
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.ServerCommand = ServerCommand;
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   EurekaJView.instrumentationGroupController
// Copyright: ©2010 My Company, Inc.
// ==========================================================================
/*globals EurekaJView */

/** @class

  (Document Your Controller Here)

  @extends SC.Object
*/
EurekaJView.instrumentationGroupController = SC.ObjectController.create(
/** @scope EurekaJView.instrumentationGroupController.prototype */ {

  	pane: null,

    showPanelPane: function() {
        var pane = SC.PanelPane.create({
            layout: {
                left: 75,
				right: 75,
				top: 75,
				bottom: 75,
            },
            contentView: SC.View.extend({
                layout: {
                    top: 0,
                    left: 0,
                    bottom: 0,
                    right: 0
                },
                childViews: 'groupToolbarView mainContentView'.w(),

				groupToolbarView: SC.ToolbarView.extend({
					childViews: 'labelView'.w(),
					layout: {top: 0, left: 0, right: 0, height: 40 },
					anchorLocation: SC.ANCHOR_TOP,

					labelView: SC.LabelView.extend({
	                    layout: {centerY: 0, centerX:0, centerY: 0, height: 40, top: 10, width: 400 },
						controlSize: SC.LARGE_CONTROL_SIZE,
						fontWeight: SC.BOLD_WEIGHT,
	                    value: 'Instrumentation Groups'
	                }).classNames('whitelabel'),
				}),

				mainContentView: SC.View.extend({
					childViews: 'instrumentationGroupLeft instrumentationGroupLeftScrollView hideInstrumentationGroupButtonView'.w(),
					layout: {top: 40, bottom: 0, right: 0, left: 0},

					instrumentationGroupLeft: SC.View.design({
						childViews: 'newInstrumentationView'.w(),
						layout: {top: 0, bottom: 43, left: 0, width: 306 },
						anchorLocation: SC.ANCHOR_TOP,
						backgroundColor: "#000000",

						newInstrumentationView : SC.View.design({
							childViews: 'newGroupNameTextFieldView newGroupButtonView'.w(),
							layout: {top: 3, height: 28, left: 3, width: 300 },
							backgroundColor: "#F0F8FF",

							newGroupNameTextFieldView : SC.TextFieldView.design({
								layout: {top: 2, height: 24, centerY:0, right: 82, left: 2 },
							}),

							newGroupButtonView: SC.ButtonView.extend({
								layout: {left: 220, right: 2, height: 24, centerY: 0, top: 2, centerY: 0},
								title: "Add",
							}),
						}),

					}),

					instrumentationGroupLeftScrollView: SC.ScrollView.design({
						layout: {top: 30, bottom: 45, left: 2, width: 300 },
						hasHorizontalScroller: YES,
						hasVerticalScroller: YES,

						contentView: SC.ListView.extend({
							backgroundColor: '#F0F8FF'
						}),
					}),

					hideInstrumentationGroupButtonView: SC.ButtonView.extend({
	                    layout: {
	                        width: 80,
	                        bottom: 20,
	                        height: 24,
	                        centerX: 0
	                    },
	                    title: "Close",
	                    action: "remove",
	                    target: "EurekaJView.instrumentationGroupController.pane"
	                }),
				}),

            })
        });
        pane.append();
        this.set('pane', pane);
    }

}) ;
<commit_msg>Changed design of the Instrumentation Group panel (SproutCore).<commit_after>// ==========================================================================
// Project:   EurekaJView.instrumentationGroupController
// Copyright: ©2010 My Company, Inc.
// ==========================================================================
/*globals EurekaJView */

/** @class

  (Document Your Controller Here)

  @extends SC.Object
*/
EurekaJView.instrumentationGroupController = SC.ObjectController.create(
/** @scope EurekaJView.instrumentationGroupController.prototype */ {

  	pane: null,

    showPanelPane: function() {
        var pane = SC.PanelPane.create({
            layout: {
                centerX: 0,
				width: 870,
				top: 75,
				bottom: 75,
            },
            contentView: SC.View.extend({
                layout: {
                    top: 0,
                    left: 0,
                    bottom: 0,
                    right: 0
                },
                childViews: 'groupToolbarView mainContentView'.w(),

				groupToolbarView: SC.ToolbarView.extend({
					childViews: 'labelView'.w(),
					layout: {top: 0, left: 0, right: 0, height: 40 },
					anchorLocation: SC.ANCHOR_TOP,

					labelView: SC.LabelView.extend({
	                    layout: {centerY: 0, centerX:0, height: 40, top: 10, width: 250 },
						controlSize: SC.LARGE_CONTROL_SIZE,
						fontWeight: SC.BOLD_WEIGHT,
	                    value: 'Instrumentation Groups'
	                }).classNames('whitelabel'),
				}),

				mainContentView: SC.View.extend({
					childViews: ['instrumentationGroupLeft','instrumentationGroupLeftScrollView','hideInstrumentationGroupButtonView','groupNameLabelView','groupNameTextFieldView',
						'sourceGroupLabelView', 'sourceGroupSelectFieldView', 'selectChartsLabelView', 'selectedChartsScrollView'],
					layout: {top: 40, bottom: 0, right: 0, left: 0},

					instrumentationGroupLeft: SC.View.design({
						childViews: 'newInstrumentationView'.w(),
						layout: {top: 0, bottom: 43, left: 0, width: 306 },
						anchorLocation: SC.ANCHOR_TOP,
						backgroundColor: "#000000",

						newInstrumentationView : SC.View.design({
							childViews: 'newGroupNameTextFieldView newGroupButtonView'.w(),
							layout: {top: 3, height: 28, left: 3, width: 300 },
							backgroundColor: "#F0F8FF",

							newGroupNameTextFieldView : SC.TextFieldView.design({
								layout: {top: 2, height: 24, centerY:0, right: 82, left: 2 },
							}),

							newGroupButtonView: SC.ButtonView.extend({
								layout: {left: 220, right: 2, height: 24, centerY: 0, top: 2, centerY: 0},
								title: "Add",
							}),
						}),

					}),

					instrumentationGroupLeftScrollView: SC.ScrollView.design({
						layout: {top: 30, bottom: 45, left: 2, width: 300 },
						hasHorizontalScroller: YES,
						hasVerticalScroller: YES,

						contentView: SC.ListView.extend({
							backgroundColor: '#F0F8FF'
						}),
					}),

					groupNameLabelView: SC.LabelView.extend({
	                    layout: {left: 320, width: 180, height: 25, top: 20},
						controlSize: SC.NORMAL_CONTROL_SIZE,
	                    value: 'Instrumentation Group Name:'
	                }),

					groupNameTextFieldView: SC.TextFieldView.design({
						layout: {top: 15, height: 25, left: 515, width: 350},
					}),

					sourceGroupLabelView: SC.LabelView.extend({
	                    layout: {left: 320, width: 180, height: 25, top: 55},
						controlSize: SC.NORMAL_CONTROL_SIZE,
	                    value: 'Instrumentation Group Source:'
	                }),

					sourceGroupSelectFieldView: SC.SelectFieldView.design({
						layout: {top: 55, height: 25, left: 515, width: 350},

					  objects: [
					    {name:'For 3 Seconds', value:'3seconds'},
					    {name:'Until the browser is closed', value:'closeBrowser'},
					    {name:'For 1 year', value:'1year'}
					    ],
					  nameKey: 'name',
					  valueKey: 'value',

					  acceptsFirstResponder: function() {
					    return this.get('isEnabled');
					  }.property('isEnabled'),

					  //valueBinding: 'LoginLogoutSample.loginPageController.rememberMe'
					}),

					selectChartsLabelView: SC.LabelView.extend({
	                    layout: {left: 320, width: 180, height: 25, top: 85},
						controlSize: SC.NORMAL_CONTROL_SIZE,
	                    value: 'Select Charts:'
	                }),

					selectedChartsScrollView: SC.ScrollView.design({
						layout: {top: 85, bottom: 45, left: 515, width: 350},
						hasHorizontalScroller: YES,
						hasVerticalScroller: YES,

						contentView: SC.ListView.design({
							backgroundColor: '#F0F8FF',
							contentValueKey: "name",
							//contentBinding: 'EurekaJView.instrumentationChartController.arrangedObjects',
							//selectionBinding: 'EurekaJView.instrumentationChartController.selection'

						}),
					}),

					hideInstrumentationGroupButtonView: SC.ButtonView.extend({
	                    layout: {
	                        width: 80,
	                        bottom: 20,
	                        height: 24,
	                        centerX: 0
	                    },
	                    title: "Close",
	                    action: "remove",
	                    target: "EurekaJView.instrumentationGroupController.pane"
	                }),
				}),

            })
        });
        pane.append();
        this.set('pane', pane);
    }

}) ;
<|endoftext|>