package ru.yandex.webmaster3.api.sitemap.util;

import ru.yandex.webmaster3.api.sitemap.data.ApiSitemapId;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author avhaliullin
 */
public class SitemapIdUtil {
    private static final String UUID_REGEX_STRING = "\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12}";
    private static final Pattern ROOT_SITEMAP_REGEX = Pattern.compile("^" + UUID_REGEX_STRING + "$");
    private static final Pattern CHILD_SITEMAP_REGEX = Pattern.compile("^(" + UUID_REGEX_STRING + "):(" + UUID_REGEX_STRING + ")$");

    public static ApiSitemapId fromString(String sitemapId) {
        try {
            {
                Matcher m = ROOT_SITEMAP_REGEX.matcher(sitemapId);
                if (m.find()) {
                    UUID id = UUID.fromString(m.group());
                    return new ApiSitemapId(null, id);
                }
            }
            {
                Matcher m = CHILD_SITEMAP_REGEX.matcher(sitemapId);
                if (m.find()) {
                    UUID parentId = UUID.fromString(m.group(1));
                    UUID childId = UUID.fromString(m.group(2));
                    return new ApiSitemapId(parentId, childId);
                }
            }
        } catch (IllegalArgumentException e) {
            //ignore
        }
        return null;
    }

    public static String toString(ApiSitemapId sitemapId) {
        if (sitemapId.getParentId() == null) {
            return sitemapId.getId().toString();
        } else {
            return sitemapId.getParentId().toString() + ":" + sitemapId.getId().toString();
        }
    }
}
