/**
 * Draw chart
 */
class RenderCharts {

    constructor(highCharts) {
        this.highCharts = highCharts;
    }

    /**
     * Plot a chart
     *
     * @param id
     * @param type
     */
    draw(id, type) {
        this.data = JSON.parse($('#' + id).attr('src-data'));
        const serializedType = this.serializedType();

        this.highCharts.chart(id, {
            chart: {
                type: type,
                animation: false
            },
            title: {
                text: ''
            },
            xAxis: {
                allowDecimals: false,
                categories: this.data.categories,
                max: serializedType.length - 1
            },
            yAxis: {
                allowDecimals: false,
                gridLineColor: '#fff'
            },
            series: [{
                name: 'Options chosen',
                data: serializedType,
            }],
            legend: {
                enabled: false
            },
            annotations: {
                visible: false
            },
            plotOptions: {
                bar: {
                    dataLabels: {
                        enabled: true
                    }
                },
                pie: {
                    dataLabels: {
                        enabled: true,
                        padding: 0,
                        // style: {
                        //     fontSize: '8px'
                        // },
                        formatter: function() {
                            let sliceIndex = this.point.index;

                            return this.series.chart.axes[0].categories[sliceIndex];
                        }
                    },
                    startAngle: 90
                }
            },
        })
    }

    /**
     * Return an array contains data for series.data
     *
     * @returns {[]}
     */
    serializedType() {
        let dataSerialized = []

        this.data.id.map(answerId => {
            let number = 0;

            this.data.data.map(answerItem =>  {
                // Ignore invalid data
                if (answerItem === null || answerItem === undefined)
                    return;

                Object.keys(answerItem).map(answerItemKey => {
                    if (answerId === answerItemKey) {
                        number = ++number
                    }
                })
            });

            dataSerialized.push(number);
        })

        return dataSerialized;
    }
}

export default RenderCharts;
