package com.its.wthr.service;

import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

@Slf4j
public class AbstractXmlService {

    public NodeList getXmlNodeList(String url, String nodeTag) {
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

            URL xmlUrl = new URL(url);
            URLConnection urlConnection = xmlUrl.openConnection();
            urlConnection.setConnectTimeout(10000);   //The timeout in mills
            urlConnection.setReadTimeout(10000);

            Document document = documentBuilder.parse(urlConnection.getInputStream());

            document.getDocumentElement().normalize();
            return document.getElementsByTagName(nodeTag);
        } catch (ParserConfigurationException e) {
            log.error("getXmlNodeList(ParserConfigurationException): {}, {}: {}", url, nodeTag, e.toString());
        } catch (SAXException e) {
            log.error("getXmlNodeList(SAXException): {}, {}: {}", url, nodeTag, e.toString());
        } catch (IOException e) {
            log.error("getXmlNodeList(IOException): {}, {}: {}", url, nodeTag, e.toString());
        } catch (Exception e) {
            log.error("getXmlNodeList(Exception): {}, {}: {}", url, nodeTag, e.toString());
        }
        return null;
    }

}
