package com.queplix.tools.fkchecker.client.helpers;

import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.util.*;

/**
 * @author dmitry.antonov
 */
public class PropertiesHelper {


    private static boolean isADigit(String value) {
        ParsePosition ps = new ParsePosition(0);
        DecimalFormat.getNumberInstance().parse(value, ps);
        return ps.getErrorIndex() == -1 && ps.getIndex() == value.length();
    }

    private static class Property {
        public String getPropertyName() {
            return propertyName;
        }
        public String getPropertyValue() {
            return propertyValue;
        }
        public String getPropertySuffix() {
            return propertySuffix;
        }
        private String propertyName;
        private String propertyValue;
        private String propertySuffix;
        public Property(Map.Entry entry) {
            propertyValue = entry.getValue().toString();
            propertyName = entry.getKey().toString();
            int lastPoint = propertyName.lastIndexOf('.');
            propertySuffix = new String(propertyName.substring(lastPoint));
            propertyName = new String(propertyName.substring(0, lastPoint));
        }
    }

    private static void addPropertyIntoMap(Map<String, List<Property>> map, Map.Entry entry) {
        Property property = new Property(entry);
        List<Property> list = map.get(property.getPropertySuffix());
        if (list == null) {
            list = new ArrayList<Property>();
            map.put(property.getPropertySuffix(), list);
        }
        list.add(property);
    }

    private static Properties createProperties(List<Property> list) {
        Properties result = new Properties();
        for (Property property : list) {
            result.setProperty(property.getPropertyName(), property.getPropertyValue());
        }
        return result;
    }
    
    public static Properties[] splitProperties(Properties properties) {
        boolean isMultisource = false;
        for (Object o: properties.keySet()) {
            String[] key = ("" + o).split("\\.");
            if (isADigit(key[key.length - 1])) {
                isMultisource = true;
                break;
            }
        }
        if (isMultisource) {
            Map<String, List<Property>> map = new HashMap<String, List<Property>>();
            for (Map.Entry entry: properties.entrySet()) {
                addPropertyIntoMap(map, entry);
            }
            Properties[] result = new Properties[map.size()];
            int idx = 0;
            for (List<Property> list : map.values()) {
                result[idx++] = createProperties(list);
            }
            return result;
        }
        else {
            return new Properties[]{properties};
        }
    }
}
