angular.module('odoo')

    /**
    * -----------------------------------------------------------------------------
    *  Description:    Local storage manager for crm stage data
    * -----------------------------------------------------------------------------
    */
    .factory('crmStagesStorageFactory', function () {

        // Save crm stage data to local storage
        var save = function (crmStage, success, error) {
            var values = [
                crmStage.remote_id ? crmStage.remote_id : 0,
                crmStage.name ? crmStage.name : ''
            ];

            var sql = null;

            if (crmStage.id) {
                values.push(crmStage.id);

                sql = 'UPDATE crm_stage SET ' +
                    'remote_id = ?,' +
                    'modified = 1,' +
                    'modified_date = CURRENT_TIMESTAMP,' +
                    'name = ? ' +
                    'WHERE id = ?';
            } else {
                sql = 'INSERT INTO crm_stage(' +
                    'remote_id,' +
                    'modified,' +
                    'name) ' +
                    'VALUES (?, 0, ?)';
            }

            db.executeSql(sql, values, function (result) {
                success(sql.startsWith('INSERT') ? result.insertId : lead.id);
            }, function (err) {
                error(err);
            });
        }

        /**
         * Remove all crm stages from local storage
         */
        var removeAll = function (success, error) {
            var sql = 'DELETE FROM crm_stage';

            db.executeSql(sql, [], function(result) {
                success(result.rowsAffected);
            }, function(err) {
                error(err);
            });
        }

        return {
            save: save,
            removeAll: removeAll
        }
    });