/*
 * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class AppId {

    private static Logger LOGGER = Logger.getLogger(AppId.class.getSimpleName());
    private static final String RESPONSE_FORMATTED_FILE = "response_unformatted.xml";
    private static final String RESPONSE_TAG = ":applicationID";

    public static void main(String[] args) {

        try {

            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new File(RESPONSE_FORMATTED_FILE));

            NodeList tagName = doc.getElementsByTagName("ns:return");
            String prefix = null;

            if (tagName.item(0) != null) {
                Element appElement1 = (Element) tagName.item(0);

                String tagAttr = appElement1.getAttribute("xsi:type");

                if(tagAttr != null) {
                    String[] str = tagAttr.split(":", 0);
                    prefix = str[0];

                } else {
                    LOGGER.info("type attribute not found.");
                }

            } else {
                LOGGER.info("return tag not found.");
            }

            NodeList appId = doc.getDocumentElement().getElementsByTagName(prefix+RESPONSE_TAG);

            if (appId.item(0) != null) {
                Element appElement = (Element) appId.item(0);
                NodeList appList = appElement.getChildNodes();

                // This stdout is added to be read by the shell script.
                System.out.println(((Node) appList.item(0)).getNodeValue().trim());

            } else {
                LOGGER.info("Application ID not found.");
            }

        } catch (SAXParseException err) {
            LOGGER.info("** Parsing error" + ", line "
                    + err.getLineNumber() + ", uri " + err.getSystemId());
            System.exit(-1);

        } catch (SAXException e) {
            LOGGER.info("** SAX error" + " " + e.getMessage());
            System.exit(-1);

        } catch (ParserConfigurationException er) {
            LOGGER.info("** Parser configuration error" + " " + er.getMessage());
            System.exit(-1);

        } catch (IOException error) {
            LOGGER.info("** Error occurred" + " " + error.getMessage());
            System.exit(-1);
        }

        System.exit(0);
    }
}
