package com.bb.util;



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.security.MessageDigest;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;


public class IPKit {

    public static String getIpAddressByRequest(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        
        String[] ipArray = ip.split(",");
        ip = ipArray[0];
        
        return ip;
    }

    public static String getIpAddressByRequest1(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }

        ip = request.getHeader("X-Real-IP");
        if(!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }
    
    public static String viewPage(HttpServletRequest request, String page) {
    	  HttpSession session = request.getSession(true);
    	  
    String userAgent = request.getHeader("user-agent");
    String referer = request.getHeader("referer");
    String vt = "";
    if(!(request.getParameter("vt") == null || "".equals(request.getParameter("vt")))) {
    	vt = request.getParameter("vt");
    			
		if("M".equals(vt)) {
	    	session.setAttribute("isMobile", "mobile");
	    }
		
		if("W".equals(vt)) {
	    	session.setAttribute("isMobile", "web");
	    }
    }else {
    	session.setAttribute("isMobile", "");
    }
    
    
    
    
    
    Boolean isMobile = false;

    String url = request.getRequestURI();
    String domain = request.getRequestURL().toString().replace(request.getRequestURI(),"/");

    String viewName=page;
    isMobile = userAgent.contains("Mobile/")
         || userAgent.contains("Android")
         || userAgent.contains("iPhone")
         || userAgent.contains("iPad");

 
    if(isMobile) {
        viewName = "mobile/"+viewName;
    } else {
        
     
	        if("mobile".equals(session.getAttribute("isMobile").toString())) {
	        	  return "mobile/"+viewName;
	        }else {
	        	  return  "front/"+viewName;
	        }
        
        
    }
    
    return viewName;
    
}
    
    
    public static String shaEnc(String base) { 
	

	try{

		MessageDigest digest = MessageDigest.getInstance("SHA-256");
			byte[] hash = digest.digest(base.getBytes("UTF-8"));
			StringBuffer hexString = new StringBuffer();
	
			for (int i = 0; i < hash.length; i++) {
				String hex = Integer.toHexString(0xff & hash[i]);
				if(hex.length() == 1) hexString.append('0');
				hexString.append(hex);
			}
	
			//출력
			return hexString.toString();
	
		} catch(Exception ex){
			throw new RuntimeException(ex);
		}
	}
    
    
    // Add Firewall rule
    public static void allowInboundTraffic(String LOG_PREFIX, String ipAddress) throws Exception {
        if (ipAddress == null || ipAddress.isEmpty()) {
            throw new IllegalArgumentException("IP address cannot be null or empty");
        }

        // Split the IP addresses if multiple are provided, separated by commas
        String[] ipAddresses = ipAddress.split(",");

        for (String ip : ipAddresses) {
            ip = ip.trim(); // Remove any leading or trailing spaces
            if (ip.isEmpty()) {
                continue; // Skip empty entries
            }

            String family;
            try {
                InetAddress inetAddress = InetAddress.getByName(ip);
                if (inetAddress instanceof Inet6Address) {
                    family = "ipv6";
                } else if (inetAddress instanceof Inet4Address) {
                    family = "ipv4";
                } else {
                    throw new IllegalArgumentException("Unknown IP address type: " + ip);
                }
            } catch (Exception e) {
                throw new IllegalArgumentException("Invalid IP address: " + ip, e);
            }

            // Commands to allow inbound traffic for ports 80 and 443
            String[] commands = {
                String.format("sudo firewall-cmd --permanent --add-rich-rule='rule family=\"%s\" source address=\"%s\" port protocol=\"tcp\" port=\"80\" accept'", family, ip),
                String.format("sudo firewall-cmd --permanent --add-rich-rule='rule family=\"%s\" source address=\"%s\" port protocol=\"tcp\" port=\"443\" accept'", family, ip)
            };

            for (String command : commands) {
                executeCommand(command);
            }
        }

        // 마지막에 한 번만 reload!
        executeCommand("sudo firewall-cmd --reload");
    }

    // Execute shell command
    private static void executeCommand(String command) throws Exception {
        System.out.println("실행중: " + command);
        Process process = Runtime.getRuntime().exec(new String[] { "bash", "-c", command }); // bash shell 사용 권장
        int exitCode = process.waitFor();

        if (exitCode != 0) {
            try (BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
                StringBuilder errorMessage = new StringBuilder();
                String line;
                while ((line = errorReader.readLine()) != null) {
                    errorMessage.append(line).append("\n");
                }
                throw new RuntimeException("Error executing command: " + command + "\n" + errorMessage.toString());
            }
        } else {
            try (BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = outputReader.readLine()) != null) {
                    System.out.println(line);
                }
            }
        }
    }
}
