// called to test if thresholds must be visible or not
// if it contains NaN values, display is not correct
Array.prototype.containsNaN = function() {

    for(var i = 1; i < this.length; i++)
    {
        if(isNaN(this[i]))
            return false;
    }

    return true;
}

// called to test if thresholds contains
// only null or others values (numbers)

Array.prototype.isLegendVisible = function() {

    for(var i = 1; i < this.length; i++)
    {
		// here we have a number, legend must be visible
		if(this[i] !== null) return true;
    }
    return false;
}

// We define common properties share by all kinds of charts to generate them
const chartConfig = {
  titleSize: '1.6em',
  titleColor: '#555555',
  subTitleSize: '1.2em',
  subTitleColor: '#555555',
  subTitleWeight: 'normal',
  legendFontSize: '1.2em',
  legendFontColor: '#333333',
  legendFontWeight: 'normal',
  xAxisFontSize: '1.3em',
  xAxisFontColor: '#6a6d9b',
  yAxisFontSize: '1.3em',
  yAxisFontColor: '#999999',
  yAxisTitleSize: '1.4em',
  yAxisTitleColor: '#777777',
};

// console.log(input);
$( document ).ready(function() {

	// if not specified we let highchart handling min value on yAxis
	if(isNaN(input["indicator-force-min"])) input["indicator-force-min"] = null;

	// if missing values, we display it
	if(input["indicator-missing-values"].length > 0) {
		chart_subtitle = input['indicator-no-data-notice'].replace('%s', input["indicator-missing-values"].join(", "));
		chartConfig.subTitleSize = '1.2em';
		chartConfig.subTitleColor = '#ff4c4c';
		chartConfig.subTitleWeight = 'bold';
	} else {
		chart_subtitle = null;
	}

	// to change color palette
		if(input["indicator-colors"] !== undefined ) {
			// console.log('indicator-colors is passed !');
			Highcharts.setOptions({
			 colors: input['indicator-colors']
		});
		}

	// no title, we reduce margin top to maximize chart canvas
	if(input['indicator-notitle'] === 1) {
		tmargin = 40;
		chart_title = null;
		chart_subtitle = null;
	} else {
		tmargin = 120;

		if(input['indicator-wanted-vis']  === 'pie' || input['indicator-wanted-vis']  === 'donut'  || input['indicator-wanted-vis']  === 'treemap') chart_title = input['indicator-name'] + ' ' +   input['indicator-wanted-year'];
		else chart_title = input['indicator-name'];
		if(input['indicator-wanted-vis']  === 'pie' || input['indicator-wanted-vis']  === 'donut'  || input['indicator-wanted-vis']  === 'treemap') chart_subtitle = input['indicator-unit'] + ' ' + input['indicator-negative-notice'] ;
	}

	if(input['site-language'] == 'fr') {
		Highcharts.setOptions({
			lang: {
				decimalPoint: ',',
				thousandsSep: ' '
			}
		});
	}
	// console.log("indicator type : " + input['indicator-type']);
	// console.log("wanted vis : " + input['indicator-wanted-vis']);
	// console.log("Default vis : " + input['indicator-default-vis']);
	if(input['indicator-wanted-vis'] === 'line') input['indicator-wanted-vis'] = 'spline';

	/** We must populate the chart
	*	We get values from array
	*/
	var dates = [];
	var thresholds = [];
	var values = [];

	// console.log('thresholds : ');
	// console.log(input['thresholds']);

	if(input['indicator-type']  === 'unique') {

		if(input["indicator-colors"] !== undefined ) {
			dataColor = input["indicator-colors"][0];
			thresholdColor = input["indicator-colors"][1];
		} else {
			dataColor = input["indicator-serie-color"];
			// thresholdColor = Highcharts.getOptions().colors[3];
			thresholdColor = input['indicator-threshold-color'];
		}

		// console.log(input['data']);
		// console.log(input['dates']);
		// console.log(input['thresholds']);

		// see api : http://api.highcharts.com/highcharts
		$('#main-chart-container').highcharts({
			plotOptions: {
				column: {
					pointPadding: 0.2,
					borderWidth: 0
				}
			},
			title: {
				text: chart_title,
				align: 'left',
				style:  {
					color: chartConfig.titleColor,
					fontSize: chartConfig.titleSize
				}
			},
			subtitle: {
				text: chart_subtitle,
				align: 'left',
				style:  {
					color: chartConfig.subTitleColor,
					fontSize: chartConfig.subTitleSize,
					fontWeight: chartConfig.subTitleWeight
				}
			},
			legend: {
				align: 'right',
				verticalAlign: 'top',
				layout: 'horizontal',
				x: -30,
				y: 0,
				itemStyle: {
				  color: chartConfig.legendFontColor,
				  fontSize: chartConfig.legendFontSize,
				  fontWeight: chartConfig.legendFontWeight
				}
			},
			chart: {
				type: 'column',
				// margin: 75,
				marginTop: tmargin
			},
			credits: false,
			xAxis: {
				categories: input['dates'].reverse(),
				labels: {
					style: {
						fontSize: chartConfig.xAxisFontSize,
						color: chartConfig.xAxisFontColor
					}
				},
				crosshair: true
			},
			yAxis: {
				title: {
					text: input['indicator-unit'],
					style: {
						fontSize: chartConfig.yAxisTitleSize,
						color: chartConfig.yAxisTitleColor
					}
				},
				labels: {
					style: {
						fontSize: chartConfig.yAxisFontSize,
						color: chartConfig.yAxisFontColor
					}
				},
				// https://api.highcharts.com/highcharts/yAxis.min
				min: input["indicator-force-min"],
				startOnTick: false
			},
			labels: {
				items: [{
				   // html: '<?php echo $result_sdii[0]['sdii_name']; ?>',
					style: {
						left: '50px',
						top: '18px',
						color: (Highcharts.theme && Highcharts.theme.textColor) || '#222222'
					}
				}],
				style: {
						fontSize: '1em'
				}
			},
			tooltip: {
				headerFormat: '<b>{series.name}</b><br/>',
				pointFormat: '{point.y}',
				style: {
						fontSize: '1.2em'
					}
			},
		    responsive: {
		        rules: [{
		            condition: {
		                maxWidth: 500
		            },
		            chartOptions: {
		                legend: {
		                    align: 'center',
		                    verticalAlign: 'bottom',
		                    layout: 'horizontal'
		                },
		                yAxis: {
		                    labels: {
		                        align: 'left',
		                        x: 0,
		                        y: -5
		                    },
		                },
		                title: {
		                    text: null
		                }
		            }
		        }]
		    },
			series: [{
				type: input['indicator-wanted-vis'],
				name: input['indicator-serie-name'],
				data: input['data'].reverse(),
				color: dataColor
			}, {
				type: 'spline',
				name: input['indicator-threshold-name'],
				data: input['thresholds'].reverse(),
				color: thresholdColor,
				dashStyle: 'ShortDot',
				showInLegend: input['thresholds'].isLegendVisible(),
				visible: input['thresholds'].containsNaN(),
				marker: {
					lineWidth: 2,
					symbol: 'circle',
					lineColor: thresholdColor,
					fillColor: 'white'
				}
			}]
		});

	} // closing input['indicator-type']  === 'unique' test

	// we check input['indicator-type']  === 'multiple' AND input['indicator-wanted-year'] IS NULL
	// if(input['indicator-type']  === 'multiple' && input['indicator-wanted-year'] == null) {
	if(input['indicator-type']  === 'multiple' && input['indicator-multiple-type']  === 'sum' && input['indicator-wanted-year'] == null) {

		if(input["indicator-stack-type"] !== undefined ) {
			stackType = input["indicator-stack-type"];
			stackUnit = (input["indicator-stack-type"] == 'normal') ? input['indicator-unit'] : "% - " + input['indicator-unit']; // if 'percent' we set unit
		} else {
			stackType = 'normal';
			stackUnit = input['indicator-unit'];
		}
		if(input['indicator-wanted-vis'] == 'area' || input['indicator-wanted-vis'] == 'spline'  ) {
			shift = 0.5; // put 0.5 to fill the gap (but create half size catgories) - see https://stackoverflow.com/questions/74727962/highchart-stretch-representation-on-full-width-xaxis-behavior/74730643?noredirect=1#comment131911207_74730643
			tickPlacement = 'on';
		} else {
			shift = 0;
			tickPlacement = 'between';
		}
		// console.log(input['data']);
		// console.log(input['dates']);
		// console.log(input['thresholds']);

		var jsonObj = JSON.parse(input['data']);
		// console.log(jsonObj);


		// finally we add threshold as spline
		if(input['thresholds'].length > 0) {
			item = {}
			marker = {}
			marker ['lineWidth'] = 2;
			marker ['symbol'] = 'circle';
			// marker ['lineColor'] = Highcharts.getOptions().colors[3];
			marker ['lineColor'] = input['indicator-threshold-color'];
			marker ['fillColor'] = 'white';
			item ["type"] = 'spline';
			item ["name"] = input['indicator-threshold-name'];
			item ["data"] = input['thresholds'].reverse();
			// item ["color"] = Highcharts.getOptions().colors[3];
			item ["color"]  = input['indicator-threshold-color'];
			item ["dashStyle"] = 'ShortDot';
			item ["marker"] = marker;
			item ["showInLegend"] = input['thresholds'].isLegendVisible();
			jsonObj.push(item);
		}


		// see api : http://api.highcharts.com/highcharts
		var chart = $('#main-chart-container').highcharts({
			title: {
				text: chart_title,
				align: 'center',
				style:  {
					color: chartConfig.titleColor,
					fontSize: chartConfig.titleSize
				}
			},
			subtitle: {
				text: chart_subtitle,
				align: 'center',
				style:  {
					color: chartConfig.subTitleColor,
					fontSize: chartConfig.subTitleSize,
					fontWeight: chartConfig.subTitleWeight
				}
			},
			legend: {
				align: 'right',
				verticalAlign: 'top',
				layout: 'horizontal',
				// x: -100,
				y: 0,
				itemStyle: {
				  color: chartConfig.legendFontColor,
				  fontSize: chartConfig.legendFontSize,
				  fontWeight: chartConfig.legendFontWeight
				}

			},
			chart: {
				type: input['indicator-wanted-vis'],
				// margin: 75,
				marginTop: tmargin,
			},
			credits: false,
			xAxis: {
				// https://stackoverflow.com/questions/74727962/highchart-stretch-representation-on-full-width-xaxis-behavior/74730643#74730643
				min: shift,
				max: input['dates'].length- (1 + shift),
				categories: input['dates'].reverse(),
				tickWidth: 1,
				tickmarkPlacement: tickPlacement,
				labels: {
					style: {
						fontSize: chartConfig.xAxisFontSize,
						color: chartConfig.xAxisFontColor
					}
				}
			},
			yAxis: {
				title: {
					text: stackUnit,
					style: {
						fontSize: chartConfig.yAxisTitleSize,
						color: chartConfig.yAxisTitleColor
					},
				},
				labels: {
					style: {
						fontSize: chartConfig.yAxisFontSize,
						color: chartConfig.yAxisFontColor
					}
				},
				stackLabels: {
					enabled: true,
					style: {
						fontWeight: 'bold',
						fontSize: '1.4em',
						textOutline: 0,
						color: (Highcharts.theme && Highcharts.theme.textColor) || '#222222'
					}
				},
				// https://api.highcharts.com/highcharts/yAxis.min
				min: input["indicator-force-min"],
				startOnTick: false
			},
			responsive: {
		        rules: [{
		            condition: {
		                maxWidth: 600
		            },
		            chartOptions: {
		                legend: {
		                    align: 'center',
		                    verticalAlign: 'bottom',
		                    layout: 'horizontal'
		                },
		                yAxis: {
		                    labels: {
		                        align: 'left',
		                        x: 0,
		                        y: -5
		                    },
		                }
		            }
		        },
		        {
		            condition: {
		                maxWidth: 500
		            },
		            chartOptions: {
		                legend: {
		                    enabled: false
		                }
		            }
		        }]
		    },
			plotOptions: {
				series: {
					stacking: stackType // 'percent' or 'normal'
				},
				column: {
					dataLabels: {
						enabled: true,
						color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
						style: {
							textShadow: 'none',
							textOutline: 0,
							fontSize: '1.2em'
						},
						enabled: false
					}
				},
				area: {
					lineColor: '#ffffff',
					lineWidth: 1,
					marker: {
						enabled: false,
						lineWidth: 1,
						lineColor: '#ffffff'
					},
					dataLabels: {
						enabled: false,
						color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
						style: {
							textShadow: 'none'
						}
					}
				}
			},
			tooltip: {
				headerFormat: '<b>{point.x}</b><br/>',
				pointFormat: '{series.name}: {point.y} ({point.percentage:,.2f} %)',
				style: {
						fontSize: '1.2em'
				}
				// valueDecimals: 2
			},
			series: jsonObj
		});
	} // closing input['indicator-type']  === 'multiple' test opening around line 160

	if(input['indicator-type']  === 'multiple' && input['indicator-multiple-type']  !== 'sum' && input['indicator-wanted-year'] == null) {

		if(input['indicator-wanted-vis'] == 'area' || input['indicator-wanted-vis'] == 'spline'  ) {
			shift = 0.5; // put 0.5 to fill the gap (but create half size catgories) - see https://stackoverflow.com/questions/74727962/highchart-stretch-representation-on-full-width-xaxis-behavior/74730643?noredirect=1#comment131911207_74730643
			tickPlacement = 'on';
		} else {
			shift = 0;
			tickPlacement = 'between';
		}

		if(input["indicator-colors"] !== undefined ) {
			dataColor = input["indicator-colors"][0];
			thresholdColor = input["indicator-colors"][1];
			meanColor = '#333333';
		} else {
			dataColor = input["indicator-serie-color"];
			// thresholdColor = Highcharts.getOptions().colors[3];
			thresholdColor = input['indicator-threshold-color'];
			meanColor = '#333333';
		}

		var jsonObj = JSON.parse(input['data']);
		//var jsonObj = JSON.parse(input['data-mean']);
		// console.log(jsonObj);

		// we dynamically add threshold if set
		var threshold = {
			type: 'spline',
			name: input['indicator-threshold-name'],
			data: input['thresholds'].reverse(),
			color: thresholdColor,
			dashStyle: 'ShortDot',
			showInLegend: input['thresholds'].isLegendVisible(),
			visible: input['thresholds'].containsNaN(),
			marker: {
			lineWidth: 2,
				symbol: 'circle',
				lineColor: thresholdColor,
				fillColor: 'white'
			}
		}

		if(input['indicator-multiple-type']  == 'mean') {
			// we dynamically add threshold if set
			var mean = {
				type: 'spline',
				name: input['indicator-mean-name'],
				data: input['data-mean'].reverse(),
				color: meanColor,
				dashStyle: 'ShortDash',
				showInLegend: input['data-mean'].isLegendVisible(),
				visible: input['data-mean'].containsNaN(),
				marker: {
					lineWidth: 2,
					symbol: 'circle',
					lineColor: meanColor,
					fillColor: 'white'
				}
			}
			jsonObj.push(mean);
		}

		jsonObj.push(threshold);
		// console.log(jsonObj);

		// see api : http://api.highcharts.com/highcharts
		var chart = $('#main-chart-container').highcharts({
			title: {
				text: chart_title,
				align: 'center',
				style:  {
					color: chartConfig.titleColor,
					fontSize: chartConfig.titleSize
				}
			},
			subtitle: {
				text: chart_subtitle,
				align: 'center',
				style:  {
					color: chartConfig.subTitleColor,
					fontSize: chartConfig.subTitleSize,
					fontWeight: chartConfig.subTitleWeight
				}
			},
			legend: {
				align: 'right',
				verticalAlign: 'top',
				layout: 'horizontal',
				// x: -100,
				y: 0,
				itemStyle: {
					color: chartConfig.legendFontColor,
					fontSize: chartConfig.legendFontSize,
					fontWeight: chartConfig.legendFontWeight
				}

			},
			chart: {
				type: input['indicator-wanted-vis'],
				// margin: 75,
				marginTop: tmargin,
			},
			credits: false,
			xAxis: {
				categories: input['dates'].reverse(),
				min: shift,
				max: input['dates'].length- (1 + shift),
				tickWidth: 1,
				tickmarkPlacement: tickPlacement,
				labels: {
					style: {
						fontSize: chartConfig.xAxisFontSize,
						color: chartConfig.xAxisFontColor
					}
				},
				crosshair: true
			},
			yAxis: {
				title: {
					text: input['indicator-unit'],
					style: {
						fontSize: chartConfig.yAxisTitleSize,
						color: chartConfig.yAxisTitleColor
					}
				},
				labels: {
					style: {
						fontSize: chartConfig.yAxisFontSize,
						color: chartConfig.yAxisFontColor
					}
				},
				// https://api.highcharts.com/highcharts/yAxis.min
				min: input["indicator-force-min"],
				startOnTick: false
			},
			labels: {
				items: [{
					// html: '<?php echo $result_sdii[0]['sdii_name']; ?>',
					style: {
						left: '50px',
						top: '18px',
						color: (Highcharts.theme && Highcharts.theme.textColor) || '#222222'
					}
				}],
				style: {
					fontSize: '1em'
				}
			},
			tooltip: {
				headerFormat: '<b>{point.x}</b><br/>',
				pointFormat: '{series.name}: {point.y}',
				style: {
					fontSize: '1.2em'
				}
				// valueDecimals: 2
			},
			responsive: {
				rules: [{
					condition: {
						maxWidth: 500
					},
					chartOptions: {
						legend: {
							align: 'center',
							verticalAlign: 'bottom',
							layout: 'horizontal'
						},
						yAxis: {
							labels: {
								align: 'left',
								x: 0,
								y: -5
							},
						},
						title: {
							text: null
						}
					}
				}]
			},
			plotOptions: {
				column: {
					pointPadding: 0.1,
					borderWidth: 0
				}
			},
			series: jsonObj
		});
	}

	// Generate Pie charts for a given year
		if(input['indicator-wanted-vis']  === 'pie' && input['indicator-wanted-year'] !== null) {

			if (typeof input['vis-pie-size'] !== 'undefined') var userInnerSize = input['vis-pie-size'];
			else var userInnerSize = '0%';

		 // console.log(input['data']);

		 var chart = $('#main-chart-container').highcharts({
			chart: {
				type: 'pie',
			},
			credits: false,
			title: {
				text: chart_title,
				style:  {
					color: chartConfig.titleColor,
					fontSize: chartConfig.titleSize
				}
			},
			 subtitle: {
				 text: chart_subtitle,
				 style:  {
					 color: chartConfig.subTitleColor,
					 fontSize: chartConfig.subTitleSize,
					 fontWeight: chartConfig.subTitleWeight
				 }
			 },
			tooltip: {
				pointFormat: '<b>{series.name}</b> : {point.y} ({point.percentage:,.2f} %)',
				style: {
					fontSize: '1.2em',
					color:'#222222'
		        }
			},
			plotOptions: {
				pie: {
					allowPointSelect: true,
					cursor: 'pointer',
					depth: 35,
					dataLabels: {
						enabled: true,
						format: '{point.name}<br /><span style="color:#8C8C8C">{point.percentage:,.2f} %</span>',
						style: {
							textShadow: 'none',
							fontSize: '1.2em',
							color:'#222222'
		                }
					}
				}
			},
			responsive: {
				rules: [{
				      condition: {
				        maxWidth: 600
				      },
				      chartOptions: {
				        plotOptions: {
				          pie: {
				            dataLabels: {
				              enabled: false
				            }
				          }
				        }
				      }
				    }]
		    },
			series: [{
				type: 'pie',
				innerSize: userInnerSize,
				name: input['indicator-unit'],
				data: input['data']
			}]
		});

		return false;

    }  // closing input['indicator-wanted-vis']  === 'pie' test


		// Generate treemap charts for a given year
		if(input['indicator-wanted-vis']  === 'treemap' && input['indicator-wanted-year'] !== null) {

			var jsonObj = JSON.parse(input['data']);

			var chart = $('#main-chart-container').highcharts({

				colorAxis: {
		            // minColor: '#D9B1EF',
		            // minColor: '#FFBC75',
		            minColor: input['color1'],
		            // maxColor: '#AE69D3' //Highcharts.getOptions().colors[0]
		            // maxColor: '#EA9C4D'
		            maxColor: input['color2']
		        },
		        credits: false,
		        series: [{
		            type: 'treemap',
		            layoutAlgorithm: 'squarified',
		            data: jsonObj,
		            dataLabels: {
		            	enabled: true,
		                style: {
		                	textOutline: 0,
		                	fontSize: '1.2em',
		                	color: '#222222'
		                }
		            }
		        }],
		        legend: {
		            enabled: false
		        },
		        tooltip: {
		            pointFormat: '<b>{point.name}</b> : {point.value} ' + input['indicator-unit'],
		            style: {
					fontSize: '1.2em',
					color:'#222222'
		        }
		        },
				subtitle: {
					text: chart_subtitle,
					style:  {
						color: chartConfig.subTitleColor,
						fontSize: chartConfig.subTitleSize,
						fontWeight: chartConfig.subTitleWeight
					}
				},
		        title: {
		            text: chart_title,
		            style:  {
						color: '#777777',
						fontSize: '1.6em'
					}
		        }
		    });
	}  // closing input['indicator-wanted-vis']  === 'treemap' test


});