angular.module('odoo')

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

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

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

        /**
         *
         */
        var remove = function (opportunity, success, error) {
            var values = [opportunity.id];
            var sql = null;

            if (opportunity.remote_id) {
                sql = 'UPDATE lead SET modified = 2 WHERE id = ?';
            } else {
                sql = 'DELETE FROM lead WHERE id = ?'
            }

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

        /**
         *
         */
        var removeAll = function (success, error) {
            var sql = "DELETE FROM lead WHERE type = 'opportunity'";

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

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