<%@ page import="java.util.regex.*" %>
<%@ page import="com.google.gson.*" %>
<%@ include file="utils.jspf" %>
<%@ page import="javax.xml.parsers.DocumentBuilderFactory, javax.xml.parsers.DocumentBuilder" %>
<%@ page import="org.w3c.dom.Document, org.w3c.dom.NodeList" %>
<%@ page import="org.w3c.dom.Node, org.w3c.dom.Element" %>

<%!
    boolean correctMapBuild = true;
    boolean correctChartsBuild = true;
    boolean compatibleBuild = false;
    boolean moveForward = false;
    boolean isMapBuildPresent = false;
    boolean isChartsBuildPresent = false;

    String[] pathsToCheck = {
        "/plugins/VitaraCharts",
        "/plugins/VitaraCharts/utils/CheckHealth/",
        "/plugins/VitaraCharts/utils/CheckHealth/state.properties",
        "/plugins/VitaraMaps",
        "/plugins/VitaraMaps/utils/CheckHealth/",
        "/plugins/VitaraMaps/utils/CheckHealth/state.properties",
        "/WEB-INF",
        "/WEB-INF/web.xml",
    };
    public List<String> getUnreadablePaths(ServletContext application, String[] pathsToCheck) {
        List<String> unreadable = new ArrayList<>();
        for (String path : pathsToCheck) {
            String realPath = application.getRealPath(path);
            if (realPath == null) {
                // unreadable.add(path + " (realPath null)");
                continue;
            }
            File file = new File(realPath);
            if(!file.exists()) continue;
            if (!file.canRead()) {
                unreadable.add(path);
            }
        }
        return unreadable;
    }
    class Error{
        String status;
        Map<String, String> errors = new HashMap<>();
        Map<String, String> warnings = new HashMap<>();
        Map<String, Object> extraInfo = new HashMap<>();
        Error(String errMsg) {
            this.status = "fail";
            this.errors.put("File Persmission", errMsg);
        }
    }
    class VersionCompatibility {
        String status;
        Map<String, String> errors = new HashMap<>();
        Map<String, String> warnings = new HashMap<>();
        Map<String, Object> extraInfo = new HashMap<>();
        List<String> resolutions;

        VersionCompatibility(boolean correctPlatformBuild, boolean correctMapBuild, boolean correctChartsBuild, boolean compatibleBuild) {
            this.resolutions = new ArrayList<>();
            if (!correctPlatformBuild) {
                this.errors.put("Platform Build", "Incorrect platform-specific build");
                this.resolutions.add(resolutionMessages.getOrDefault("E08", "Please Add Correct Build"));
            }
            if (!correctMapBuild) {
                this.warnings.put("Map Build", "Map build not correct");
                this.resolutions.add(resolutionMessages.getOrDefault("E09", "Please Add Correct Map Build"));
            }
            if (!correctChartsBuild) {
                this.warnings.put("Charts Build", "Charts build not correct");
                this.resolutions.add(resolutionMessages.getOrDefault("E10", "Please Add Correct Charts Build"));
            }
            if (!compatibleBuild) {
                if (isChartsBuildPresent && isMapBuildPresent) {
                    this.warnings.put("Compatibility Check", "Map & Chart Build not compatible");
                    this.resolutions.add(resolutionMessages.getOrDefault("E11", "Please Add Compatible Build"));
                }
            }

            // Determine status
            if (!this.errors.isEmpty()) {
                this.status = "fail";
            } else if (!this.warnings.isEmpty()) {
                this.status = "passWithWarnings";
            } else {
                this.status = "pass";
            }
        }
    }
    // Helper method to validate the other plugin
    void validatePluginCompatibility(ServletContext application, String pluginPath, String pluginType,
        String platformName, String currPluginVer) {
        if (!isPluginPresent(application, pluginPath)) return;

        Properties prop = readStateProperties(getRealPath(application, pluginPath + "utils/CheckHealth/state.properties"));
        String otherPlatform = prop.getProperty("app.platform");
        String otherVersion = prop.getProperty("app.version");

        if(otherPlatform == null || otherVersion == null) {
            return;
        }

        boolean isPlatformMatch = platformName.equals(otherPlatform);
        boolean isVersionCompatible = currPluginVer.substring(0, 2).equals(otherVersion.substring(0, 2));

        if (pluginType.contains("Maps")) {
            isMapBuildPresent = true;
            correctMapBuild = isPlatformMatch;
        } else {
            isChartsBuildPresent = true;
            correctChartsBuild = isPlatformMatch;
        }

        compatibleBuild = isVersionCompatible;
    }
    String getWebXmlForPlatform(ServletContext application) {
        return application.getRealPath("/WEB-INF/web.xml");
    }
%>

<%   
    List<String> unreadablePaths = getUnreadablePaths(application, pathsToCheck);

    if (unreadablePaths.isEmpty()) {
        String platformName = "";
        String subPlatFormName = "";

        File platformXmlFile = new File(getWebXmlForPlatform(application));
        if (platformXmlFile.exists() && platformXmlFile.canRead()) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(platformXmlFile);

            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName("display-name");
            NodeList paramList = doc.getElementsByTagName("param-value");
            if(paramList.getLength() > 0) {
                Node node = paramList.item(0);
                subPlatFormName = node.getTextContent();
            }
            if (nodeList.getLength() > 0) {
                Node node = nodeList.item(0);
                platformName = node.getTextContent();
            }
            if (platformName.equals("Web Tier")){
                platformName = "MicroStrategy";
                if (subPlatFormName.equals("mobile")) {
                    platformName = "MicroStrategyMobile";
                }
            }else if (platformName.equals("Library")) {
                platformName = "MicroStrategyLibrary";
            }
        } else {
            // Define the folder path
            String checkHealthFolderPath = getRealPath(application, "").replace("\\", "/");
            // Extract platform name using regex
            Pattern pattern = Pattern.compile("/webapps/([^/]+)/plugins");
            Matcher matcher = pattern.matcher(checkHealthFolderPath);
            platformName = matcher.find() ? matcher.group(1) : "Not Found";
        }
        // Read state.properties for the current plugin

        Properties prop = readStateProperties(getRealPath(application, "VitaraCharts/utils/CheckHealth/state.properties"));    
        String currPluginPlatform = prop.getProperty("app.platform");
        String currPluginVer = prop.getProperty("app.version");
        String currPluginName = prop.getProperty("app.name");

        // Initialize validation flags
        boolean correctPlatformBuild = platformName.equals(currPluginPlatform);

        // Usage
        switch (currPluginName) {
            case "VitaraCharts":
                isChartsBuildPresent = true;
                validatePluginCompatibility(application, "VitaraMaps/", "Maps", platformName, currPluginVer);
                break;
            case "VitaraMaps":
                isMapBuildPresent = true;
                validatePluginCompatibility(application, "VitaraCharts/", "Charts", platformName, currPluginVer);
                break;
            case "VitaraMapsLibrary":
                isMapBuildPresent = true;
                validatePluginCompatibility(application, "VitaraChartsLibrary/", "Charts", platformName, currPluginVer);
                break;
            case "VitaraChartsLibrary":
                isChartsBuildPresent = true;
                validatePluginCompatibility(application, "VitaraMapsLibrary/", "Maps", platformName, currPluginVer);
                break;
        }

        VersionCompatibility result = new VersionCompatibility(correctPlatformBuild, correctMapBuild, correctChartsBuild, compatibleBuild);

        // Set response type as JSON
        Gson gson = new Gson();
        String json = gson.toJson(result);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        out.print(json);
        out.flush();
    } else  {
        Error result = new Error("Enought File persmission not present to execute CheckHealth");
        Gson gson = new Gson();
        String json = gson.toJson(result);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        out.print(json);
        out.flush();

    }
        
%>
