package com.lemon.lifecenter.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.spec.AlgorithmParameterSpec;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class LifeCenterFunction {
    public static String setURLEncode(String content, String lngType) throws UnsupportedEncodingException {
        return URLEncoder.encode(content, lngType);
    }

    public static String setURLDecode(String content, String lngType) throws UnsupportedEncodingException {
        return URLDecoder.decode(content, lngType);
    }

    public static String aesEncrypt(String encKey, byte[] iv, String paramInput) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec key = new SecretKeySpec(encKey.getBytes("UTF-8"), "AES");

        cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));

        byte[] cipherText = cipher.doFinal(paramInput.getBytes("UTF-8"));

        return Base64.getEncoder().encodeToString(cipherText);
    }

    public static String aesDecrypt(String encKey, byte[] iv, String paramInput) throws Exception {
        byte[] textBytes = Base64.getDecoder().decode(paramInput);
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        SecretKeySpec newKey = new SecretKeySpec(encKey.getBytes("UTF-8"), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);

        return new String(cipher.doFinal(textBytes), "UTF-8");
    }

    public static ArrayList<HashMap<String, String>> parseJSON(String jsonString) {
        ArrayList<HashMap<String, String>> rtn = new ArrayList<HashMap<String, String>>();

        try {
            JSONArray array = new JSONArray(jsonString);

            for (int i = 0; i < array.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();

                JSONObject object = array.getJSONObject(i);
                Iterator<?> keys = object.keys();

                while (keys.hasNext()) {
                    String key = (String) keys.next();
                    String val = "";

                    if (object.isNull(key)) {
                        val = "";
                    } else {
                        if (object.get(key) instanceof Integer) {
                            val = String.valueOf(object.getInt(key));
                        } else if (object.get(key) instanceof Long) {
                            val = String.valueOf(object.getLong(key));
                        } else if (object.get(key) instanceof Double) {
                            val = String.valueOf(object.getDouble(key));
                        } else {
                            val = object.getString(key).equals(null) ? "" : object.getString(key);
                        }
                    }

                    map.put(key, val);
                }

                rtn.add(i, map);

                map = null;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return rtn;
    }

    public static String getRandomUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String exportOnlyNumber(String input) {
        return input.replaceAll("[^0-9?!\\.]", "");
    }

    public static String getNow() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();

        return dateFormat.format(date);
    }

    public static String getNow(String format) {
        DateFormat dateFormat = new SimpleDateFormat(format);
        Date date = new Date();

        return dateFormat.format(date);
    }

    public static long getNowUnixTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    public static long setFormatUnixTimeStamp(String data) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long timeStamp = 0;

        try {
            long time = dateFormat.parse(data).getTime();
            timeStamp = time / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return timeStamp;
    }

    public static String setFormatDateFromUnixTimeStamp(Date data) {
        SimpleDateFormat transFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        return transFormat.format(data);
    }

    public static String getRandomNumber(int maxSize) {
        Random rand = new Random();
        String code = "";

        for (int i = 0; i < maxSize; i++) {
            code += rand.nextInt(9);
        }

        return code;
    }

    public static void scriptMessage(HttpServletResponse response, String script) {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out;

        try {
            out = response.getWriter();
            out.println("<script>" + script + "</script>");
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getRemoteAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");

        if (ip == null) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }

    public static String setPhoneFormat(String number) {
        StringBuilder sb = new StringBuilder(15);
        StringBuilder temp = new StringBuilder(number);
        int tempLength = temp.length();

        if (tempLength == 3) {
            sb.append(number);
        } else {
            while (tempLength < 10) {
                temp.insert(0, "0");
            }

            char[] chars = temp.toString().toCharArray();

            int size = chars.length;

            if (size < 11) {
                for (int i = 0; i < size; i++) {
                    if (i == 3) {
                        sb.append("-");
                    } else if (i == 6) {
                        sb.append("-");
                    }

                    sb.append(chars[i]);
                }
            } else {
                for (int i = 0; i < size; i++) {
                    if (i == 3) {
                        sb.append("-");
                    } else if (i == 7) {
                        sb.append("-");
                    }

                    sb.append(chars[i]);
                }
            }
        }

        return sb.toString();
    }
    
    public static String removeTag(String html) throws Exception {
        return html.replaceAll("<(/)?([a-zA-Z]*)(\\s[a-zA-Z]*=[^>]*)?(\\s)*(/)?>", "");
    }
}
