<commit_before>"use strict";

var Backbone = require('../../shim/backbone'),
    _ = require('lodash'),
    App = require('../app'),
    coreModels = require('../core/models');

var ModelPackageControlModel = Backbone.Model.extend({
    defaults: {
        name: ''
    }
});

var ModelPackageControlsCollection = Backbone.Collection.extend({
    model: ModelPackageControlModel
});

var ModelPackageModel = Backbone.Model.extend();

var Tr55TaskModel = coreModels.TaskModel.extend({});

var ResultModel = Backbone.Model.extend({});

var ResultCollection = Backbone.Collection.extend({
    model: ResultModel
});

var ProjectModel = Backbone.Model.extend({
    urlRoot: '/api/modeling/projects/',

    defaults: {
        name: '',
        created_at: null,          // Date
        area_of_interest: null,    // GeoJSON
        model_package: '',         // Package name
        taskModel: null,           // TaskModel
        scenarios: null,            // ScenariosCollection
        uid: null
    },

    initialize: function() {
        var scenarios = this.get('scenarios');
        if (scenarios === null || typeof scenarios === 'string') {
            this.set('scenarios', new ScenariosCollection());
        }
        // TODO: For a new project, users will eventually
        // be able to choose which modeling package
        // they want to use in their project. For
        // now, the only option is TR55, so it is
        // hard-coded here.
        this.set('model_package', 'tr-55');
        this.set('taskModel', new Tr55TaskModel());
        this.set('uid', App.user.get('uid'));

        this.listenTo(this.get('scenarios'), 'add', this.addIdsToScenarios, this);
        this.on('change:name', this.saveProjectAndScenarios, this);
    },

    updateName: function(newName) {
        // TODO: Having fetched a users list of projects,
        // ensure that this new name is unique prior to saving
        this.set('name', newName);
    },

    saveProjectAndScenarios: function() {
        if (App.user.get('uid') !== this.get('uid')) {
            return;
        }

        if (!this.get('id')) {
            // We haven't saved the project before, save the project and then
            // set the project ID on each scenario, then reattach the senarios
            // to the project.
            var self = this;
            this.save()
                .done(function() {
                    self.updateProjectScenarios(self.get('id'), self.get('scenarios'));
                })
                .fail(function() {
                    console.log('Failed to save project');
                });
        } else {
            this.save()
                .fail(function() {
                    console.log('Failed to save project');
                });
        }
    },

    addIdsToScenarios: function() {
        var projectId = this.get('id');
        if (!projectId) {
            this.saveProjectAndScenarios();
        } else {
            this.updateProjectScenarios(projectId, this.get('scenarios'));
        }
    },

    updateProjectScenarios: function(projectId, scenarios) {
        scenarios.each(function(scenario) {
            if (!scenario.get('project')) {
                scenario.set('project', projectId);
            }
        });
    },

    parse: function(response, options) {
        if (response.scenarios) {
            // If we returned scenarios (probably from a GET) then set them.
            var uid = response.uid = response.user.id,
                scenariosCollection = this.get('scenarios'),
                scenarios = _.map(response.scenarios, function(scenario) {
                    var scenarioModel = new ScenarioModel(scenario);
                    scenarioModel.set('uid', uid);
                    scenarioModel.get('modifications').reset(scenario.modifications);
                    return scenarioModel;
                });
            scenariosCollection.reset(scenarios);
            // Set the uid to ensure controls are properly set.
            response.uid = uid;

            delete response.scenarios;
        }

        // TODO: Does this hurt anything if we always set.
        response.taskModel = new Tr55TaskModel();

        return response;
    }
});

var ModificationModel = coreModels.GeoModel.extend({
    defaults: _.extend({
            name: '',
            type: ''
        }, coreModels.GeoModel.prototype.defaults
    )
});

var ModificationsCollection = Backbone.Collection.extend({
    model: ModificationModel
});

// Static method to create an instance of this collection.
// This lets us create a collection from an array of raw objects (web app)
// or from an array of models (unit tests).
ModificationsCollection.create = function(data) {
    if (data instanceof ModificationsCollection) {
        return data;
    } else {
        return new ModificationsCollection(data);
    }
};

var ScenarioModel = Backbone.Model.extend({
    urlRoot: '/api/modeling/scenarios/',

    defaults: {
        name: '',
        is_current_conditions: false,
        modifications: null,      // ModificationsCollection
        active: false,
        uid: null
    },

    initialize: function(attrs, options) {
        Backbone.Model.prototype.initialize.apply(this, arguments);
        this.set('uid', App.user.get('uid'));
        this.set('modifications', ModificationsCollection.create(attrs.modifications));

        this.on('change:project change:name', this.attemptSave, this);
        this.get('modifications').on('add remove', this.attemptSave, this);
    },

    attemptSave: function() {
        if (App.user.get('uid') !== this.get('uid')) {
            return;
        }
        this.save().fail(function() {
            console.log('Failed to save scenario');
        });
    },

    getSlug: function() {
        var slug = this.get('name')
                       .toLowerCase()
                       .replace(/ /g, '-') // Spaces to hyphens<commit_msg>Don't autosave data for guest users.<commit_after>"use strict";

var Backbone = require('../../shim/backbone'),
    _ = require('lodash'),
    App = require('../app'),
    coreModels = require('../core/models');

var ModelPackageControlModel = Backbone.Model.extend({
    defaults: {
        name: ''
    }
});

var ModelPackageControlsCollection = Backbone.Collection.extend({
    model: ModelPackageControlModel
});

var ModelPackageModel = Backbone.Model.extend();

var Tr55TaskModel = coreModels.TaskModel.extend({});

var ResultModel = Backbone.Model.extend({});

var ResultCollection = Backbone.Collection.extend({
    model: ResultModel
});

var ProjectModel = Backbone.Model.extend({
    urlRoot: '/api/modeling/projects/',

    defaults: {
        name: '',
        created_at: null,          // Date
        area_of_interest: null,    // GeoJSON
        model_package: '',         // Package name
        taskModel: null,           // TaskModel
        scenarios: null,            // ScenariosCollection
        uid: null
    },

    initialize: function() {
        var scenarios = this.get('scenarios');
        if (scenarios === null || typeof scenarios === 'string') {
            this.set('scenarios', new ScenariosCollection());
        }
        // TODO: For a new project, users will eventually
        // be able to choose which modeling package
        // they want to use in their project. For
        // now, the only option is TR55, so it is
        // hard-coded here.
        this.set('model_package', 'tr-55');
        this.set('taskModel', new Tr55TaskModel());
        this.set('uid', App.user.get('uid'));

        this.listenTo(this.get('scenarios'), 'add', this.addIdsToScenarios, this);
        this.on('change:name', this.saveProjectAndScenarios, this);
    },

    updateName: function(newName) {
        // TODO: Having fetched a users list of projects,
        // ensure that this new name is unique prior to saving
        this.set('name', newName);
    },

    saveProjectAndScenarios: function() {
        if (App.user.get('uid') !== this.get('uid') || App.user.get('uid') < 1) {
            return;
        }

        if (!this.get('id')) {
            // We haven't saved the project before, save the project and then
            // set the project ID on each scenario, then reattach the senarios
            // to the project.
            var self = this;
            this.save()
                .done(function() {
                    self.updateProjectScenarios(self.get('id'), self.get('scenarios'));
                })
                .fail(function() {
                    console.log('Failed to save project');
                });
        } else {
            this.save()
                .fail(function() {
                    console.log('Failed to save project');
                });
        }
    },

    addIdsToScenarios: function() {
        var projectId = this.get('id');
        if (!projectId) {
            this.saveProjectAndScenarios();
        } else {
            this.updateProjectScenarios(projectId, this.get('scenarios'));
        }
    },

    updateProjectScenarios: function(projectId, scenarios) {
        scenarios.each(function(scenario) {
            if (!scenario.get('project')) {
                scenario.set('project', projectId);
            }
        });
    },

    parse: function(response, options) {
        if (response.scenarios) {
            // If we returned scenarios (probably from a GET) then set them.
            var uid = response.uid = response.user.id,
                scenariosCollection = this.get('scenarios'),
                scenarios = _.map(response.scenarios, function(scenario) {
                    var scenarioModel = new ScenarioModel(scenario);
                    scenarioModel.set('uid', uid);
                    scenarioModel.get('modifications').reset(scenario.modifications);
                    return scenarioModel;
                });
            scenariosCollection.reset(scenarios);
            // Set the uid to ensure controls are properly set.
            response.uid = uid;

            delete response.scenarios;
        }

        // TODO: Does this hurt anything if we always set.
        response.taskModel = new Tr55TaskModel();

        return response;
    }
});

var ModificationModel = coreModels.GeoModel.extend({
    defaults: _.extend({
            name: '',
            type: ''
        }, coreModels.GeoModel.prototype.defaults
    )
});

var ModificationsCollection = Backbone.Collection.extend({
    model: ModificationModel
});

// Static method to create an instance of this collection.
// This lets us create a collection from an array of raw objects (web app)
// or from an array of models (unit tests).
ModificationsCollection.create = function(data) {
    if (data instanceof ModificationsCollection) {
        return data;
    } else {
        return new ModificationsCollection(data);
    }
};

var ScenarioModel = Backbone.Model.extend({
    urlRoot: '/api/modeling/scenarios/',

    defaults: {
        name: '',
        is_current_conditions: false,
        modifications: null,      // ModificationsCollection
        active: false,
        uid: null
    },

    initialize: function(attrs, options) {
        Backbone.Model.prototype.initialize.apply(this, arguments);
        this.set('uid', App.user.get('uid'));
        this.set('modifications', ModificationsCollection.create(attrs.modifications));

        this.on('change:project change:name', this.attemptSave, this);
        this.get('modifications').on('add remove', this.attemptSave, this);
    },

    attemptSave: function() {
        if (App.user.get('uid') !== this.get('uid') || App.user.get('uid') < 1) {
            return;
        }
        this.save().fail(function() {
            console.log('Failed to save scenario');
        });
    },

    getSlug: function() {
        var slug = this.get('name')
                       .toLowerCase()
                       .replace(/ /g, '-') // Spaces to hyphens
{'fraction_non_alphanumeric': 0.12722263961933383, 'fraction_numerical': 0.0018365472910927456, 'mean_word_length': 2.0017539463793534, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2343632', 'n_tokens_mistral': 3238, 'n_tokens_neox': 3166, 'n_words': 780}