package ru.yandex.wmconsole.viewer.api;

import ru.yandex.wmconsole.data.sitemaps.SitemapSourceEnum;
import ru.yandex.wmconsole.error.ClientException;
import ru.yandex.wmconsole.error.ClientProblem;
import ru.yandex.wmconsole.viewer.api.servantlet.ApiParameterNames;
import ru.yandex.wmconsole.viewer.sitemap.SitemapId;

/**
 * @author aherman
 */
public class SitemapIdApiFormatter {
    private static final char IN_SEARCH_SITEMAP_FLAG = 'S';
    private static final char LATEST_SITEMAP_FLAG = 'L';

    public static String toExternalId(SitemapId sitemapId) {
        StringBuilder sb = new StringBuilder(16);
        toExternalId(sb, sitemapId);
        return sb.toString();
    }

    static void toExternalId(StringBuilder sb, SitemapId sitemapId) {
        switch(sitemapId.getSitemapSource()) {
            case IN_SEARCH:
                sb.append(IN_SEARCH_SITEMAP_FLAG);
                break;

            case LATEST:
                sb.append(LATEST_SITEMAP_FLAG);
                break;

            default:
                throw new IllegalArgumentException("Unsupported sitemap id");
        }

        sb.append(':');
        sb.append(sitemapId.getSitemapId());
    }

    public static SitemapId parseFromExternalId(String externalId) throws ClientException {
        int colon = externalId.indexOf(':');
        if (colon != 1) {
            throw new ClientException(ClientProblem.ILLEGAL_PARAM_VALUE, "Illegal parameter value: " + ApiParameterNames.SITEMAP_ID);
        }
        char flag = externalId.charAt(0);
        SitemapSourceEnum sitemapSource;
        switch(flag) {
            case IN_SEARCH_SITEMAP_FLAG:
                sitemapSource = SitemapSourceEnum.IN_SEARCH;
                break;

            case LATEST_SITEMAP_FLAG:
                sitemapSource = SitemapSourceEnum.LATEST;
                break;

            default:
                throw new ClientException(ClientProblem.ILLEGAL_PARAM_VALUE, "Illegal parameter value: " + ApiParameterNames.SITEMAP_ID);
        }

        long sitemapId;
        try {
            sitemapId = Long.parseLong(externalId.substring(colon + 1));
        } catch (NumberFormatException e) {
            throw new ClientException(ClientProblem.ILLEGAL_PARAM_VALUE, "Illegal parameter value: " + ApiParameterNames.SITEMAP_ID);
        }

        return new SitemapId(sitemapId, sitemapSource);
    }
}
