package com.queplix.core.client.controls.charts;

import com.queplix.core.client.app.vo.ChartFieldDataRequest;
import com.queplix.core.client.app.vo.ChartFieldMeta;
import com.queplix.core.client.app.vo.ChartFieldOnDemandData;
import com.queplix.core.client.app.vo.chart.ChartDataItem;
import com.queplix.core.client.app.vo.chart.ChartType;
import com.queplix.core.client.controls.QFormElementControllerImpl;
import com.queplix.core.client.controls.QFormElementModel;
import com.queplix.core.client.controls.QFormElementView;
import com.queplix.core.client.controls.charts.QChartView;

class QChartControllerImpl extends QFormElementControllerImpl
        implements QChartController, QChartView.ViewListener {
    
    private QChartModelImpl model;
    private QChartViewImpl view;
    
    private boolean isInitialized = false;

    public QChartControllerImpl(
            QChartModelImpl model, QChartViewImpl view){

        this.model = model;
        this.view = view;
        this.view.addListener(this);
    }
    
    protected QFormElementModel getModel() {
        return model;
    }

    protected QFormElementView getView() {
        return view;
    }

    public void onChartTypeChanged(ChartType type) {
        requestChartData(type);
    }

    public void onClick(ChartDataItem item) {
        // TODO Auto-generated method stub
    }

    public void onDataRequested() {
        ChartFieldOnDemandData onDemandData = model.getOnDemandData();
        // try to obtain current charts' type
        ChartType type = onDemandData != null
                ? onDemandData.getChartType() : null;
        requestChartData(type);
    }
    
    public void onEmptyDataRequested() {
        ChartFieldOnDemandData onDemandData = model.getOnDemandData();
        // try to obtain current charts' type
        ChartType type = onDemandData != null
                ? onDemandData.getChartType() : null;
        requestChartData(type, true);
    }
    
    public void onInit() {
        super.onInit();
        isInitialized = true;
        requestChartData(null, true);
    }

    private void requestChartData(ChartType type) {
        requestChartData(type, view.isSearchMode());
    }
    
    private void requestChartData(ChartType type, boolean empty) {
        if(!isInitialized)
            return;

        ChartFieldMeta meta = model.getMeta();
        ChartFieldDataRequest request = new ChartFieldDataRequest(
                meta.getFieldID(), meta.getChartName(), empty);
        request.setChartType(type);
        controlEventsListener.needMoreData(request);
    }
    

}
