package com.sifang.modules.sys.util;

import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author gaols
 */
public class ParaUtils {
    /**
     * @param map The original parameters map.
     * @return the para map which map every para to the very first value.
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> getParasMap(Map map) {
        Map<String, String> parasMap = new HashMap<>();
        Set set = map.entrySet();
        for (Object v : set) {
            Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>) v;
            String[] value = entry.getValue();

            String ret = null;
            if (value != null) {
                ret = value.length > 1 ? StringUtils.join(value, ",") : value[0];
            }

            parasMap.put(entry.getKey(), ret);
        }
        return parasMap;
    }

    public static String formatParas(Map<String, String> parasMap, String header) {
        Set<Map.Entry<String, String>> set = parasMap.entrySet();
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("%s%n", header));
        sb.append("-----------------------------------------------\n");
        for (Map.Entry<String, String> entry : set) {
            sb.append(String.format("%30s:  %s%n", entry.getKey(), entry.getValue()));
        }
        sb.append("-----------------------------------------------\n");
        return sb.toString();
    }

    public static boolean hasValues(Map<String, String> map) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (!Objects.equals(entry.getKey(), "page") && !Objects.equals(entry.getKey(), "limit") && StringUtils.isNotBlank(entry.getValue())) {
                return true;
            }
        }
        return false;
    }

    public static Map<String, Object> getParasObjectMap(Map<String, String[]> parameterMap) {
        Map<String, Object> parasMap = new HashMap<>();
        Set<Map.Entry<String, String[]>> set = parameterMap.entrySet();
        for (Map.Entry<String, String[]> v : set) {
            String[] value = v.getValue();
            String ret = null;
            if (value != null) {
                ret = value.length > 1 ? StringUtils.join(value, ",") : value[0];
            }
            parasMap.put(v.getKey(), ret);
        }
        return parasMap;
    }
}
