package gov.va.med.edp.dao.rpc;

import gov.va.med.edp.rpc.VistaLinkDaoSupport;
import gov.va.med.edp.vo.BigBoardDebugInfoVO;
import gov.va.med.edp.dao.ServerPackageVersionDao;

import java.util.Map;
import java.util.HashMap;
import java.io.StringReader;
import java.io.IOException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataRetrievalFailureException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

/**
 * TODO: document VistaLinkServerPackageVersionDao
 */
public class VistaLinkServerPackageVersionDao extends VistaLinkBigBoardDao implements ServerPackageVersionDao {
    private static final String UNABLE_TO_GET_VERSION_INFO = "unable to get version info";    

    public String getServerPackageVersion(String stationNumber) {
        Map params = new HashMap();
        params.put("command", "initTracking");
        String result = executeCommand(stationNumber, null, params);
        return getVersion(result);
    }

    public BigBoardDebugInfoVO getVistaLinkConnectionInfo(String stationNumber) throws DataAccessException {
    	return getRpcTemplate().getVistaLinkConnectionInfo(stationNumber, EDPTRACKING_APPLICATION_USER);
    }    
    
    private String getVersion(String result) {
        Document doc = buildDocument(result);
        return getVersion(doc);
    }   
    
    private Element getUserElement(Document doc) {
        return (Element) doc.getDocumentElement().getElementsByTagName("user").item(0);
    }

    private String getVersion(Document doc) {
        Element user = getUserElement(doc);
        if (user == null) return null;
        return user.getAttribute("version");
    }

    private Document buildDocument(String result) {
           try {
               DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
               return builder.parse(new InputSource(new StringReader("<results>" + result + "</results>")));
           } catch (ParserConfigurationException e) {
               throw new DataRetrievalFailureException(UNABLE_TO_GET_VERSION_INFO, e);
           } catch (IOException e) {
               throw new DataRetrievalFailureException(UNABLE_TO_GET_VERSION_INFO, e);
           } catch (SAXException e) {
               throw new DataRetrievalFailureException(UNABLE_TO_GET_VERSION_INFO, e);
           }
       }

}
