package com.siemens.ui.client.data;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.dom.client.Node;
import com.google.gwt.user.client.Element;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.data.XMLTools;
import com.smartgwt.client.types.DSDataFormat;

public final class SectionDataSource extends DataSource {

  public SectionDataSource(String id, String xPath, String dataURL) {
    this.setID(id);
    this.setRecordXPath(xPath);
    this.setDataURL(dataURL);
    this.setClientOnly(true);
    this.setDataFormat(DSDataFormat.XML);
  }

  @Override
  protected Object transformRequest(DSRequest dsRequest) {
    return super.transformRequest(dsRequest);
  }

  @Override
  protected void transformResponse(DSResponse response, DSRequest request, Object data) {
    JsArray<Element> nodes = ((JavaScriptObject) XMLTools.selectNodes(data, this.getRecordXPath())).cast();

    Record[] records = new Record[nodes.length()];

    for (int i = 0; i < nodes.length(); i++) {
      Element element = nodes.get(i);
      Node child = element.getChild(0);
      Record record = new Record();
      record.setAttribute(this.getRecordXPath(), child.getNodeName());
      records[i] = record;
    }

    response.setData(records);

    super.transformResponse(response, request, data);
  }
}
