angular.module('odoo')

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

        /**
         *
         */
        var pull = function (id, success, error) {
            if (id) {

                odooFactory.read('crm.case.stage', [['id', '=', id]], function (response) {
                    success(response);
                }, function (odooErr) {
                    error(odooErr);
                });

            } else {

                odooFactory.read('crm.case.stage', [], function (response) {
                    success(response);
                }, function (odooErr) {
                    error(odooErr)
                });

            }
        }

        /**
         *
         */
        var push = function (id, data, success, error) {
            // TODO
        }

        /**
         *
         */
        var destroy = function (id, success, error) {
            // TODO
        }

        /**
         *
         */
        var getAll = function (success, error) {
            sqlFactory.select('crm_stage', function (stages) {
                var data = [];

                for (var i = 0; i < stages.length; i++) {
                    data.push(stages.item(i));
                }

                success(data);
            }, function (selectErr) {
                error(selectErr);
            });
        }

        /**
         *
         */
        var sync = function (success, error) {
            pull(0, function (stages) {
                crmStagesStorageFactory.removeAll(function () {
                    asyncLoopFactory(stages.length, function (loop) {
                        var data = stages[loop.iteration()];

                        data.remote_id = data.id;
                        delete data.id;

                        crmStagesStorageFactory.save(data, function (stageId) {
                            loop.next();
                        }, function (saveErr) {
                            console.log(saveErr);
                            loop.next();
                        });

                        // end loop
                    }, function () {
                        success(stages);
                    });
                }, function (removeAllErr) {
                    error(removeAllErr);
                });
            }, function (pullErr) {
                error(pullErr);
            });
        }

        return {
            pull: pull,
            push: push,
            destroy: destroy,
            getAll: getAll,
            sync: sync
        }

    });