package com.smartgwt.sample.showcase.server;

import com.isomorphic.datasource.DSRequest;
import com.isomorphic.datasource.DSResponse;
import com.isomorphic.rpc.RPCManager;

import java.util.Map;

/**
 * New DMI for demonstrating textMatchStyle difficulties when performing server requests.
 */
public class MyCustomWorldDMI {

    private final String additionalCountry_operationID = "additionalCountry";

    public DSResponse fetch(DSRequest dsRequest) throws Exception {
        // just to make sure that this request settings are not influencing fetchAdditionalCountry
        dsRequest.setTextMatchStyle(null);

        System.out.println("DMI is executed");

        // imagine that to process the request we need some additional entity from another DS
        // to keep it simple lets reuse worldDS again
        if (!additionalCountry_operationID.equals(dsRequest.getOperationId())) {
            fetchAdditionalCountry(dsRequest.getRPCManager());
        }

        return dsRequest.execute();
    }

    private void fetchAdditionalCountry(RPCManager rpcManager) throws Exception {
        DSRequest serverSideRequest = new DSRequest("worldDS", "fetch", rpcManager);
        serverSideRequest.setCriteria("countryCode", "LO");
        serverSideRequest.setOperationId(additionalCountry_operationID);
        // no textMatchStyle for serverSideRequest, expecting DS.defaultTextMatchStyle to be used
        serverSideRequest.setTextMatchStyle(null);

        final DSResponse dsResponse = serverSideRequest.execute();
        // SELECT worldDS.countryCode, worldDS.countryName, worldDS.capital, worldDS.government, worldDS.continent, worldDS.independence, worldDS.area, worldDS.population, worldDS.gdp, worldDS.member_g8
        // FROM worldDS WHERE (LOWER(worldDS.countryCode)='lo')

        final Map dataMap = dsResponse.getDataMap();
        final String countryName = (String) dataMap.get("countryName");

        System.out.println("Btw " + countryName + " has code SK and not LO ;)");
    }
}
