import { Injectable } from '@angular/core';

@Injectable()
export class StackedAreaChartService {

    getElephantData() {
        return new Promise(function(resolve) {

            let windowObj: any = window;
            let d3 = windowObj.d3;

            d3.csv('app/components/stacked-area-chart/elephants.csv', function(data) {

                let uvData = {};

                const categories = "categories";
                const dataset = "dataset";
                const categoryKey = "Region/State";
                const populationIn2002Key = 'Elephant Population - 2002';
                const populationIn2007Key = 'Elephant Population - 2007';
                const populationIn2012Key = 'Elephant Population - 2012';

                uvData[categories] = [];
                uvData[dataset] = {};

                data.forEach(function(item) {
                    uvData[categories].push(item[categoryKey]);

                    if (!uvData[dataset][item[categoryKey]]) {
                        uvData[dataset][item[categoryKey]] = [];
                    }

                    uvData[dataset][item[categoryKey]]
                        .push({
                            name: 2002,
                            value: +item[populationIn2002Key]
                        },
                        {
                            name: 2007,
                            value: +item[populationIn2007Key]
                        }
                        , {
                            name: 2012,
                            value: +item[populationIn2012Key]
                        });
                });

                resolve(uvData);
            });
        });
    };
}
