poconsole.factory('Card', function($q, $http, $log){
    var service = {};

    service.getCardDates = function() {
        var deferred = $q.defer();
        $http.get('/api/card_dates').success(function(data) {
            var dateList = data;
            var dates = dateList.map(function(x){return {dtime:Date.create(x, {fromUTC: true}), ind:x};}).reverse();
            deferred.resolve(dates);
        });
        return deferred.promise;
    };

    service.getCardPageForDate = function(date_str, page_id){
        var deferred = $q.defer();
        $http.get('/api/cardsbydate/'+ date_str + "/" + page_id).success(function(data) {
            deferred.resolve(data);
        });
        return deferred.promise;
    };

    service.getCard = function(id){
        var deferred = $q.defer();
        $http.get('/api/cards/' + id).success(function(data) {
            deferred.resolve(data);
        });
        return deferred.promise;
    };

    service.getMultipleCards = function(card_list){
        var url = '/api/cards?q={"filters":[{"name":"_id","op":"in","val":[' + card_list.join(',') + ']}]}';
        var deferred = $q.defer();
        $http.get(url).success(function(data){
            deferred.resolve(data.objects);
        });
        return deferred.promise;
    };

    service.getLatestCard = function(){
        var deferred = $q.defer();
        $http.get('/api/cards?q={"order_by":[{"field":"created_on","direction":"desc"}], "limit":1}').success(function(data) {
            deferred.resolve(data.objects[0]);
        });
        return deferred.promise;
    };

    service.getCardGraphOptions = function(surface, downhole){
        var limits = {
            sMaxPos: surface.map(function(x){return x.position;}).reduce(function(y,z){return Math.max(y,z);})+ 20,
            sMinPos: surface.map(function(x){return x.position;}).reduce(function(y,z){return Math.min(y,z);})- 20,
            sMaxLoad: surface.map(function(x){return x.load;}).reduce(function(y,z){return Math.max(y,z);})+ 2000,
            sMinLoad: surface.map(function(x){return x.load;}).reduce(function(y,z){return Math.min(y,z);})- 2000,
            dMaxLoad: downhole.map(function(x){return x.load;}).reduce(function(y,z){return Math.max(y,z);})+ 2000,
            dMinLoad: downhole.map(function(x){return x.load;}).reduce(function(y,z){return Math.min(y,z);})- 2000,
        };

        var surfaceOptions = {
            axes: {
                x: {
                    key: 'position',
                    labelFunction: function(value) {
                        return value;
                    },
                    type: 'linear',
                    min: limits.sMinPos,
                    max: limits.sMaxPos,
                    ticks: 7
                },
                y: {
                    type: 'linear',
                    min: limits.sMinLoad,
                    max: limits.sMaxLoad,
                    ticks: 5
                }
            },
            series: [
                {
                    axis:"y",
                    key: 'load',
                    dataset: 'surface',
                    color: 'steelblue',
                    type: ['line', 'area'],
                    striped: true,
                    label: 'Surface Card',
                    id: "surfaceCard"
                }
            ],
            grid: {
                x: true,
                y: true
            }
        };
        var downholeOptions = {
            axes: {
                x: {
                    key: 'position',
                    labelFunction: function(value) {
                        return value;
                    },
                    type: 'linear',
                    min: limits.sMinPos,
                    max: limits.sMaxPos,
                    ticks: 7
                },
                y: {
                    type: 'linear',
                    min: limits.dMinLoad,
                    max: limits.dMaxLoad,
                    ticks: 5
                }
            },
            series: [
                {
                    axis:"y",
                    key: 'load',
                    dataset: 'downhole',
                    color: 'steelblue',
                    type: ['line', 'area'],
                    label: 'Downhole Card',
                    id: "downholeCard",
                }
            ],
            grid: {
                x: true,
                y: true
            }
        };
        return({surf: surfaceOptions, down: downholeOptions});
    };

    service.getCardGraphOptionsMultiple = function(graph_data){
        var colors = ['#d7191c','#fdae61','#abdda4','#2b83ba'];
        var surfaceData = [];
        var downholeData = [];
        var allSurface = [];
        var allDownhole = [];
        Object.keys(graph_data).forEach(function(card_part){
            var card_params = card_part.split("_");
            if (card_params[0] == "surface"){
                surfaceData[parseInt(card_params[1])] = graph_data[card_part];
                Array.prototype.push.apply(allSurface, graph_data[card_part]);
            } else if (card_params[0] == "downhole") {
                downholeData[parseInt(card_params[1])] = graph_data[card_part];
                Array.prototype.push.apply(allDownhole, graph_data[card_part]);
            }
        });

        var limits = {
            sMaxPos: allSurface.map(function(x){return x.position;}).reduce(function(y,z){return Math.max(y,z);})+ 20,
            sMinPos: allSurface.map(function(x){return x.position;}).reduce(function(y,z){return Math.min(y,z);})- 20,
            sMaxLoad: allSurface.map(function(x){return x.load;}).reduce(function(y,z){return Math.max(y,z);})+ 2000,
            sMinLoad: allSurface.map(function(x){return x.load;}).reduce(function(y,z){return Math.min(y,z);})- 2000,
            dMaxLoad: allDownhole.map(function(x){return x.load;}).reduce(function(y,z){return Math.max(y,z);})+ 2000,
            dMinLoad: allDownhole.map(function(x){return x.load;}).reduce(function(y,z){return Math.min(y,z);})- 2000,
        };

        var surfaceOptions = {
            axes: {
                x: {
                    key: 'position',
                    labelFunction: function(value) {
                        return value;
                    },
                    type: 'linear',
                    min: limits.sMinPos,
                    max: limits.sMaxPos,
                    ticks: 7
                },
                y: {
                    type: 'linear',
                    min: limits.sMinLoad,
                    max: limits.sMaxLoad,
                    ticks: 5
                }
            },
            series: [],
            grid: {
                x: true,
                y: true
            }
        };

        Object.keys(surfaceData).forEach(function(s_card){
            var s_ser = {
                axis:"y",
                key: 'load',
                dataset: 'surface_' + s_card.toString(),
                color: colors[ parseInt(s_card) % colors.length],
                type: ['line'],
                label: "Stroke "  + s_card.toString(),
                id: "surfaceCard" + s_card.toString()
            };
            surfaceOptions.series.push(s_ser);
        });

        var downholeOptions = {
            axes: {
                x: {
                    key: 'position',
                    labelFunction: function(value) {
                        return value;
                    },
                    type: 'linear',
                    min: limits.sMinPos,
                    max: limits.sMaxPos,
                    ticks: 7
                },
                y: {
                    type: 'linear',
                    min: limits.dMinLoad,
                    max: limits.dMaxLoad,
                    ticks: 5
                }
            },
            series: [],
            grid: {
                x: true,
                y: true
            }
        };

        Object.keys(downholeData).forEach(function(d_card){
            var d_ser = {
                axis:"y",
                key: 'load',
                dataset: 'downhole_' + d_card.toString(),
                color: colors[ parseInt(d_card) % colors.length],
                type: ['line'],
                label: "Stroke " + d_card.toString(),
                id: "downholeCard" + d_card.toString()
            };
            downholeOptions.series.push(d_ser);
        });
        return {surf: surfaceOptions, down: downholeOptions};
    };

    return service;
});
