<commit_before>'use strict';
if (!module.parent) {
    console.log("Do not call formage directly. require()-ing is required.");
    process.exit(1);
}

var Class = require('sji'),
    _ = require('underscore'),
    async = require('async'),
    fields = require('./fields'),
    widgets = require('./widgets'),
    common = require('./common');
var mongoose = require.main.require('mongoose');


var FORM_EXCLUDE_FIELDS = ['__v'];


var models = {};
exports.set_models = function (mo) {
    models = mo;
};

exports.registerModel = function (name, model) {
    models[name] = model;
};

var BaseForm = exports.BaseForm = Class.extend({
    init: function (request, options) {
        this.fields = {};
        options = options || {};
        this.data = options.data || request.body || {};
        this.files = options.files || request.files || {};
        this.admin_root = request.app.path();
        this.exclude = _.extend(FORM_EXCLUDE_FIELDS, options.exclude);
        this.instance = options.instance;
        this.request = request;
        this._fields_ready = false;
        this.fieldsets = null;
        this.errors = {};
        this.static = options.static || {};
        this.static['js'] = this.static['js'] || [];
        this.static['css'] = this.static['css'] || [];
        this.static['inline-style'] = this.static['inline-style'] || [];
        this.static['inline-script'] = this.static['inline-script'] || [];
        this.static['js'].push('/js/forms.js');
        this.handle_empty = options.empty;
        this.handle_success = options.success;
        this.handle_error = options.error;
    },
    handle: function (options) {
        this.handle_empty = options.empty || this.handle_empty;
        this.handle_success = options.success || this.handle_success;
        this.handle_error = options.error || this.handle_error;
        var self = this;
        if (self.request.method.toUpperCase() === 'GET' && this.handle_empty) {
            self.render_ready(function (err) {
                self.handle_empty(err);
            });
        }
        if (self.request.method.toUpperCase() === 'POST' && this.handle_success && this.handle_error) {
            var on_error = function (error) {
                self.render_ready(function (err) {
                    self.handle_error(err || error);
                });
            };

            self.is_valid(function (err, valid) {
                if (err || !valid) {
                    on_error(err);
                }
                else {
                    self.save(function (err, result) {
                        if (err) {
                            on_error(err);
                        }
                        else {
                            self.handle_success(null, result);
                        }
                    });
                }
            });
        }
    },
    get_static: function () {
        var self = this;
        _.each(this.fields, function (field) {
            var _static = field.get_static();
            if (_static.js.length) {
                self.static.js = _.union(self.static.js, _static.js);
            }
            if (_static.css.length) {
                self.static.css = _.union(self.static.css, _static.css);
            }
        });
    },
    render_head: function () {
        var self = this;
        self.get_static();
        return common.writer_to_string(function (res) {
            self.static['js'].forEach(function (script_url) {
                if (!~script_url.indexOf('//')) script_url = self.admin_root + script_url;
                res.write('\n<script src="' + script_url + '"></script>\n');
            });
            self.static['css'].forEach(function (style_url) {
                if (!~style_url.indexOf('://')) style_url = self.admin_root + style_url;
                res.write('\n<link type="text/css" href="' + style_url + '" rel="stylesheet">\n');
            });
            self.static['inline-style'].forEach(function (inline_style) {
                res.write('\n<style>\n' + inline_style + '\n</style>\n');
            });
            self.static['inline-script'].forEach(function (inline_script) {
                res.write('\n<script>\n' + inline_script + '\n</script>\n');
            });
        }, 1000);
    },
    get_fields: function () {
        var self = this;
        Object.keys(self.fields).forEach(function (name) {
             if (~self.exclude.indexOf(name)) {
                delete self.fields[name]
            }
        });
    },
    get_value: function (field_name) {
        return this.data[field_name];
    },
    init_fields: function () {
        this.get_fields();
        for (var field_name in this.fields) {
            var value = this.get_value(field_name);
            this.fields[field_name].set(value).name = field_name;
        }
        this._fields_ready = true;
    },
    save: function (callback) {
        if (!this._fields_ready) {
            this.init_fields();
        }
        // not implemented
        if (!this.errors) {
            this.is_valid();
        }
        if (Object.keys(this.errors) > 0) {
            callback({message: 'form did not validate'});
        }
        else {
            this.actual_save(callback);
        }
    },
    actual_save: function (callback) {
        callback(new Error('not implemented'));
    },
    is_valid: function (callback) {
        var self = this;
        if (!self._fields_ready) {
            self.init_fields();
        }
        self.errors = {};
        self.clean_values = {};<commit_msg>Small refactoring<commit_after>'use strict';
if (!module.parent) {
    console.log("Do not call formage directly. require()-ing is required.");
    process.exit(1);
}

var Class = require('sji'),
    _ = require('underscore'),
    async = require('async'),
    fields = require('./fields'),
    widgets = require('./widgets'),
    common = require('./common');
var mongoose = require.main.require('mongoose');


var FORM_EXCLUDE_FIELDS = ['__v'];


var models = {};
exports.set_models = function (mo) {
    models = mo;
};

exports.registerModel = function (name, model) {
    models[name] = model;
};

var BaseForm = exports.BaseForm = Class.extend({
    init: function (request, options) {
        this.fields = {};
        options = options || {};
        this.data = options.data || request.body || {};
        this.files = options.files || request.files || {};
        this.admin_root = request.app.path();
        this.exclude = _.extend(FORM_EXCLUDE_FIELDS, options.exclude);
        this.instance = options.instance;
        this.request = request;
        this._fields_ready = false;
        this.fieldsets = null;
        this.errors = {};
        this.static = options.static || {};
        this.static['js'] = this.static['js'] || [];
        this.static['css'] = this.static['css'] || [];
        this.static['inline-style'] = this.static['inline-style'] || [];
        this.static['inline-script'] = this.static['inline-script'] || [];
        this.static['js'].push('/js/forms.js');
        this.handle_empty = options.empty;
        this.handle_success = options.success;
        this.handle_error = options.error;
    },
    handle: function (options) {
        this.handle_empty = options.empty || this.handle_empty;
        this.handle_success = options.success || this.handle_success;
        this.handle_error = options.error || this.handle_error;
        var self = this;
        if (self.request.method.toUpperCase() === 'GET' && this.handle_empty) {
            self.render_ready(function (err) {
                self.handle_empty(err);
            });
        }
        if (self.request.method.toUpperCase() === 'POST' && this.handle_success && this.handle_error) {
            var on_error = function (error) {
                self.render_ready(function (err) {
                    self.handle_error(err || error);
                });
            };

            self.is_valid(function (err, valid) {
                if (err || !valid) {
                    on_error(err);
                }
                else {
                    self.save(function (err, result) {
                        if (err) {
                            on_error(err);
                        }
                        else {
                            self.handle_success(null, result);
                        }
                    });
                }
            });
        }
    },
    get_static: function () {
        var self = this;
        _.each(this.fields, function (field) {
            var _static = field.get_static();
            if (_static.js.length) {
                self.static.js = _.union(self.static.js, _static.js);
            }
            if (_static.css.length) {
                self.static.css = _.union(self.static.css, _static.css);
            }
        });
    },
    render_head: function () {
        var self = this;
        self.get_static();
        return common.writer_to_string(function (res) {
            self.static['js'].forEach(function (script_url) {
                if (!~script_url.indexOf('//')) script_url = self.admin_root + script_url;
                res.write('\n<script src="' + script_url + '"></script>\n');
            });
            self.static['css'].forEach(function (style_url) {
                if (!~style_url.indexOf('://')) style_url = self.admin_root + style_url;
                res.write('\n<link type="text/css" href="' + style_url + '" rel="stylesheet">\n');
            });
            self.static['inline-style'].forEach(function (inline_style) {
                res.write('\n<style>\n' + inline_style + '\n</style>\n');
            });
            self.static['inline-script'].forEach(function (inline_script) {
                res.write('\n<script>\n' + inline_script + '\n</script>\n');
            });
        }, 1000);
    },
    get_fields: function () {
        var self = this;
        Object.keys(self.fields).forEach(function (name) {
             if (~self.exclude.indexOf(name)) {
                delete self.fields[name]
            }
        });
    },
    get_value: function (field_name) {
        return this.data[field_name];
    },
    init_fields: function () {
        this.get_fields();
        for (var field_name in this.fields) {
            var value = this.get_value(field_name);
            var field = this.fields[field_name].set(value);
            field.name = field_name;
        }
        this._fields_ready = true;
    },
    save: function (callback) {
        if (!this._fields_ready) {
            this.init_fields();
        }
        // not implemented
        if (!this.errors) {
            this.is_valid();
        }
        if (Object.keys(this.errors) > 0) {
            callback({message: 'form did not validate'});
        }
        else {
            this.actual_save(callback);
        }
    },
    actual_save: function (callback) {
        callback(new Error('not implemented'));
    },
    is_valid: function (callback) {
        var self = this;
        if (!self._fields_ready) {
            self.init_fields();
        }
        self.errors = {};
        self.clean_values = {};
{'fraction_non_alphanumeric': 0.15019198142691312, 'fraction_numerical': 0.0010715242432360033, 'mean_word_length': 1.7317073170731707, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 19, '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': '3984887', 'n_tokens_mistral': 3193, 'n_tokens_neox': 3120, 'n_words': 558}