angular.module('odoo')

    /**
     *
     */
    .factory('opportunitiesStorageFactory', function (
        leadsStorageFactory
    ) {

        /**
         *
         */
        var save = function (data, success, error) {
            data.type = 'opportunity';

            leadsStorageFactory.save(data, function (opportunityId) {
                success(opportunityId);
            }, function (saveErr) {
                error(saveErr);
            });
        }

        /**
         *
         */
        var remove = function (data, success, error) {
            var query = null;

            if (data.remote_id) {
                query = squel.update()
                    .table('lead')
                    .set('modified', 2)
                    .where('id', data.id);
            } else {
                query = squel.delete()
                    .from('lead')
                    .where('id', data.id);
            }

            query = query.toParam();

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

        /**
         *
         */
        var removeAll = function (success, error) {
            var query = squel.delete()
                .from('lead')
                .where('type', 'opportunity')
                .toParam();

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

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