<template>
	<div class="bar-chart" :style="wrapperStyle">
		<canvas ref="canvas"></canvas>
	</div>
</template>

<script>
import Chart from 'chart.js/auto';

export default {
	name: 'BarChart',

	props: {
		labels: { type: Array, default: () => [] },
		values: { type: Array, default: () => [] },
		datasetLabel: { type: String, default: 'Undi' },
		height: { type: [Number, String], default: 220 },
		backgroundColor: { type: [String, Array], default: 'rgba(54, 162, 235, 0.75)' },
		borderColor: { type: [String, Array], default: 'rgba(54, 162, 235, 1)' },
		borderWidth: { type: Number, default: 0 },
		borderRadius: { type: [Number, Array], default: 0 },
		options: { type: Object, default: () => ({}) }
	},

	data: () => ({
		chart: null
	}),

	computed: {
		wrapperStyle: function () {
			var h = this.height;
			var px = (typeof h === 'number') ? (h + 'px') : String(h);
			return { height: px };
		}
	},

	watch: {
		labels: function () { this.renderChart(); },
		values: function () { this.renderChart(); },
		options: {
			handler: function () { this.renderChart(); },
			deep: true
		},
		backgroundColor: function () { this.renderChart(); },
		borderColor: function () { this.renderChart(); },
		borderWidth: function () { this.renderChart(); },
		borderRadius: function () { this.renderChart(); }
	},

	mounted: function () {
		this.renderChart();
	},

	beforeDestroy: function () {
		this.destroyChart();
	},

	methods: {
		destroyChart: function () {
			if (!this.chart) return;
			try { this.chart.destroy(); } catch (e) { }
			this.chart = null;
		},

		renderChart: function () {
			this.destroyChart();
			if (!this.$refs || !this.$refs.canvas) return;

			var ctx = this.$refs.canvas.getContext('2d');
			var labels = (this.labels || []).map(function (x) { return String(x); });
			var values = (this.values || []).map(function (v) { return Number(v) || 0; });

			var baseOptions = {
				responsive: true,
				maintainAspectRatio: false,
				plugins: {
					legend: { display: false },
					tooltip: { enabled: true }
				},
				scales: {
					x: { ticks: { maxRotation: 45, minRotation: 45, autoSkip: false } },
					y: { beginAtZero: true, ticks: { precision: 0 } }
				}
			};

			// Shallow merge is enough for our use-cases (caller can override nested keys).
			var mergedOptions = Object.assign({}, baseOptions, this.options || {});

			this.chart = new Chart(ctx, {
				type: 'bar',
				data: {
					labels: labels,
					datasets: [{
						label: this.datasetLabel,
						data: values,
						backgroundColor: this.backgroundColor,
						borderColor: this.borderColor,
						borderWidth: this.borderWidth,
						borderRadius: this.borderRadius
					}]
				},
				options: mergedOptions
			});
		}
	}
};
</script>

<style scoped>
.bar-chart {
	width: 100%;
}
</style>
