package com.example.components;

import com.vaadin.flow.component.*;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.dependency.NpmPackage;
import com.vaadin.flow.shared.Registration;
import tools.jackson.databind.json.JsonMapper;

import java.util.Map;

@Tag("apex-chart")
@NpmPackage(value = "apexcharts", version = "5.15.2")
@JsModule("./components/apex-chart.ts")
public abstract class ApexChart extends Component implements HasSize {

    protected static final JsonMapper MAPPER = JsonMapper.builder().build();

    private final String chartType;

    protected ApexChart(String chartType) {
        this.chartType = chartType;
    }

    protected String getChartType() {
        return chartType;
    }

    protected void sendOptions(Map<String, Object> options) {
        getElement().callJsFunction("renderChart", MAPPER.writeValueAsString(options));
    }

    @ClientCallable
    private void onPointClick(int seriesIndex, int dataPointIndex) {
        fireEvent(new PointClickEvent(this, true, seriesIndex, dataPointIndex));
    }

    public Registration addPointClickListener(ComponentEventListener<PointClickEvent> listener) {
        return addListener(PointClickEvent.class, listener);
    }

    public static class PointClickEvent extends ComponentEvent<ApexChart> {
        private final int seriesIndex;
        private final int dataPointIndex;

        PointClickEvent(ApexChart source, boolean fromClient, int seriesIndex, int dataPointIndex) {
            super(source, fromClient);
            this.seriesIndex = seriesIndex;
            this.dataPointIndex = dataPointIndex;
        }

        public int getDataPointIndex() {
            return dataPointIndex;
        }

        public int getSeriesIndex() {
            return seriesIndex;
        }
    }
}
