angular.module('odoo')

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

        // Save crm stage data to local storage
        var save = function (data, success, error) {
            var query = null;

            if (data.id) {                
                query = squel.update()
                    .table('crm_stage')
                    .set('remote_id', data.remote_id)
                    .set('modified', 1)
                    .set('modified_date', 'CURRENT_TIMESTAMP', { dontQuote: true })
                    .set('name', data.name)
                    .where('id', data.id);
            } else {
                query = squel.insert()
                    .into('crm_stage')
                    .set('remote_id', data.remote_id)
                    .set('modified', 0)
                    .set('name', data.name);
            }

            query = query.toParam();

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

        /**
         * Remove all crm stages from local storage
         */
        var removeAll = function (success, error) {
            var query = squel
                .delete()
                .from('crm_stage')
                .toParam();

            db.executeSql(query.text, query.values, function(result) {
                success(result.rowsAffected);
            }, function(err) {
                error(err);
            });
        }

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