package com.siemens.ui.server;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.isomorphic.datasource.BasicDataSource;
import com.isomorphic.datasource.DSRequest;
import com.isomorphic.datasource.DSResponse;
import com.siemens.nkg.ejb.domain.DpcPostcode;
import com.siemens.nkg.ejb.service.MIServiceFacade;

public class ORMDataSource extends BasicDataSource {

  private static final long serialVersionUID = 4017948417281542479L;

  @SuppressWarnings("rawtypes")
  @Override
  public DSResponse executeFetch(DSRequest req) throws Exception {
    DSResponse dsResponse = new DSResponse();
    dsResponse.setSuccess();

    if (req.isPaged()) {
      if (req.getEndRow() != DSRequest.ENDROW_UNSET) {
        // if specified, endRow overrides batchSize
        if (req.getEndRow() - req.getStartRow() > req.getBatchSize()) {
          req.setBatchSize(req.getEndRow() - req.getStartRow());
        }
      }
    }

    int startRow = (int) req.getStartRow();
    int maxResults = (int) req.getEndRow();

    List data = this.loadUnits(startRow, maxResults);

    long totalRows = data.size();
    dsResponse.setTotalRows(totalRows);
    long endRow = startRow + totalRows;

    dsResponse.setStartRow(startRow);
    dsResponse.setEndRow(endRow);
    dsResponse.setData(data);

    return dsResponse;
  }

  @Override
  public DSResponse executeAdd(DSRequest req) throws Exception {
    return null;
  }

  @Override
  public DSResponse executeRemove(DSRequest req) throws Exception {
    return null;
  }

  @Override
  public DSResponse executeUpdate(DSRequest req) throws Exception {
    return null;
  }

  @SuppressWarnings("rawtypes")
  private List loadUnits(int firstResult, int maxResults) {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
    env.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
    env.put(Context.PROVIDER_URL, "localhost:1099");

    List<DpcPostcode> data = new ArrayList<DpcPostcode>();

    try {
      MIServiceFacade service = (MIServiceFacade) new InitialContext(env).lookup("nkg/MIService/remote");

      data = service.getPostcodeEntities(firstResult, maxResults);
    } catch (NamingException e) {
      e.printStackTrace();
    }

    return data;
  }
}
