angular.module('sharedModule')

.service('cartDatasource', ['$q', 'cartService', function ($q, cartService) {
    var state = {
        status: 'notInitialized',
        products: null,
        imported: null,
    };
    return {
        status: function() { return state.status; },
        products: function() { return state.products; },
        imported: function() { return state.imported; },
        getAll: getAll,
        removeProduct: removeProduct,
        removeImportedProduct: removeImportedProduct,
        removeAllProducts: removeAllProducts,
        removeAllImported: removeAllImported,
    };

    function getAll() {

        var q = $q.defer();

        state.status = 'loading';

        cartService.getItems().then(function(res) {
            
            state.products = res.data.products;
            state.imported = res.data.imported;
            state.status = 'ready';

            q.resolve(res.data.products);
        }, function(err) {
            state.status = 'failed';
            q.reject(err);
        });

        return q.promise;
    }

    function removeProduct(index) {

        var q = $q.defer();

        var removed = state.products.splice(index, 1)[0];

        cartService.removeProduct(removed.jde_item_no).then(function(res) {
            q.resolve();
        }, function(err) {
            q.reject(err);
        });

        return q.promise;
    }

    function removeImportedProduct(index) {

        var q = $q.defer();

        var removed = state.imported.splice(index, 1)[0];

        cartService.removeProduct(removed.jde_item_no).then(function(res) {
            q.resolve();
        }, function(err) {
            q.reject(err);
        });

        return q.promise;
    }

    function removeAllProducts() {

        var q = $q.defer();

        state.products.splice(0, state.products.length);

        cartService.removeAllProducts().then(function(res) {
            q.resolve();
        }, function(err) {
            q.reject(err);
        });

        return q.promise;
    }

    function removeAllImported() {

        var q = $q.defer();

        state.imported.splice(0, state.imported.length);

        cartService.removeAllImported().then(function(res) {
            q.resolve();
        }, function(err) {
            q.reject(err);
        });

        return q.promise;
    }

}]);