angular.module('odoo')

    /**
     * -----------------------------------------------------------------------------
     *  Description:    Native SQL util instructions
     * -----------------------------------------------------------------------------
     */
    .factory('sqlFactory', function () {

        /**
         *
         */
        var count = function (tableName, success, error) {
            var sql = 'SELECT COUNT(*) AS total FROM ' + tableName;

            db.executeSql(sql, [], function (result) {
                success(result.rows.item(0).total);
            }, function (err) {
                error(err);
            });
        };

        // Execute native SQL SELECT instruction
        var select = function (tableName, success, error) {
            var sql = 'SELECT * FROM ' + tableName;

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

        // Execute native SQL SELECT instruction with a constraint
        var selectByConstraint = function (tableName, constraint, success, error) {
            var sql = 'SELECT * FROM ' + tableName + ' WHERE ' + constraint;

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

        // Execute native SQL SELECT instruction with count instruction
        var count = function (tableName, success, error) {
            var sql = 'SELECT COUNT(*) AS total FROM ' + tableName;

            db.executeSql(sql, [], function (result) {
                success(result.rows.item(0).total);
            }, function (err) {
                error(err);
            });
        };

        return {
            select: select,
            selectByConstraint: selectByConstraint,
            count: count
        }
    })

    /**
     * -----------------------------------------------------------------------------
     *  Description:    Get user configuration from local database
     * -----------------------------------------------------------------------------
     */
    .factory('configFactory', function (sqlFactory) {
        return function (success, error) {
            sqlFactory.select('user', function (users) {
                if (users.length == 0) {
                    success(0);
                } else if (users.length == 1) {
                    success(users.item(0));
                } else {
                    var configs = [];
                    for (var i = 0; i < users.length; i++) {
                        configs.push(users.item(i))
                    }

                    success(configs);
                }
            }, function (err) {
                error(err);
            });
        };
    })

    /**
     * -----------------------------------------------------------------------------
     *  Description:    Async loop util v2
     * -----------------------------------------------------------------------------
     */
    .factory('asyncLoopFactory', function () {
        return function (iterations, func, callback) {
            var index = 0;
            var done = false;
            var loop = {
                next: function () {
                    if (done) {
                        return;
                    }

                    if (index < iterations) {
                        index++;
                        func(loop);

                    } else {
                        done = true;
                        callback();
                    }
                },

                iteration: function () {
                    return index - 1;
                },

                break: function () {
                    done = true;
                    callback();
                }
            };

            loop.next();
            return loop;
        }
    })

    /**
     * -----------------------------------------------------------------------------
     *  Description:    Native camera manager
     * -----------------------------------------------------------------------------
     */
    .factory('cameraFactory', function ($cordovaCamera) {

        // Take a picture using native camera
        var takePicture = function (success, error) {
            var options = {
                quality: 75,
                destinationType: Camera.DestinationType.DATA_URL,
                sourceType: Camera.PictureSourceType.CAMERA,
                allowEdit: true,
                encodingType: Camera.EncodingType.JPEG,
                targetWidth: 300,
                targetHeight: 300,
                popoverOptions: CameraPopoverOptions,
                saveToPhotoAlbum: false,
                correctOrientation: true
            };

            $cordovaCamera.getPicture(options).then(function (imageData) {
                success(imageData);
            }, function (err) {
                error(err);
            });
        };

        return {
            takePicture: takePicture
        }
    })

    /**
     * -----------------------------------------------------------------------------
     *  Description:    Native contacts manager
     * -----------------------------------------------------------------------------
     */
    .factory('contactFactory', function ($cordovaContacts) {

        // Save customer information to device contacts
        var save = function (customer, success, error) {
            if (!customer.mobile && !customer.phone && !customer.email) {
                error();
                return;
            }

            var contact = {
                name: {
                    givenName: customer.name,
                    familyName: '',
                    formatted: ''
                },
                nickname: '',
                phoneNumbers: [
                    {
                        value: customer.phone,
                        type: 'phone'
                    },
                    {
                        value: customer.mobile,
                        type: 'mobile'
                    }
                ],
                emails: [
                    {
                        value: customer.email,
                        type: 'home'
                    }
                ],
                addresses: [
                    {
                        type: 'home',
                        formatted: '',
                        streetAddress: customer.street,
                        locality: customer.city,
                        region: '',
                        postalCode: '',
                        country: 'Paraguay'
                    }
                ],
                ims: null,
                organizations: null,
                birthday: null,
                note: null,
                photos: null,
                categories: null,
                urls: null
            };

            $cordovaContacts.save(contact).then(function (result) {
                success(result);
            }, function (err) {
                error(err);
            });
        };

        return {
            save: save
        }
    });
