angular.module('sharedModule')

.service('orderDatasource', ['$q', 'orderService', function ($q, orderService) {
    var state = {
        status: 'notInitialized',
        order: null,
        total: null,
        products: null,
        orderId: null
    };
    return {
        status: function() { return state.status; },
        order: function() { return state.order; },
        total: function() { return state.total; },
        items: function() { return state.items; },
        products: function() { return state.products; },
        orderId: function() { return state.orderId; },
        getOrder: getOrder,
    };

    function getOrder(orderId) {

        var q = $q.defer();

        state.status = 'loading';

        orderService.getOrder(orderId).then(function(data) {

            if (!data.order || !data.products || !data.products.length) {
                state.status = 'failed';
                return q.reject(new Error('No order found'));
            }
            
            state.order = data.order;
            state.orderId = orderId;
            state.products = data.products;
            state.status = 'ready';
            state.total = data.products && data.products.reduce(function (sum, next) {
                return (!isNaN(next.buy_price)) ? sum + parseFloat(next.buy_price * next.qty) : sum;
            }, 0);
            state.items = data.products && data.products.reduce(function (items, next) {
                return items + parseFloat(next.qty);
            }, 0);
            q.resolve(data);
        }, function(err) {
            state.status = 'failed';
            q.reject(err);
        });

        return q.promise;
    }

}]);