package ru.yandex.webmaster3.core.proto.converter;

import org.joda.time.DateTime;
import org.joda.time.base.AbstractInstant;
import ru.yandex.webmaster3.core.data.WebmasterApplicationInfo;
import ru.yandex.webmaster3.proto.Common;
import ru.yandex.webmaster3.proto.WebmasterCommonProto;
import ru.yandex.wmtools.common.util.uri.URI2;
import ru.yandex.wmtools.common.util.uri.UriUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author aherman
 */
public class ConverterUtils {
    public static DateTime toDateTime(int protobufTime) {
        return new DateTime(TimeUnit.SECONDS.toMillis(protobufTime));
    }

    public static DateTime toDateTime(long protobufTime) {
        return new DateTime(TimeUnit.SECONDS.toMillis(protobufTime));
    }

    public static int fromDateTime(AbstractInstant dateTime) {
        return (int) TimeUnit.MILLISECONDS.toSeconds(dateTime.toDate().getTime());
    }

    public static String canonicalizeSitemapUrl(String url) {
        URI2 uri2 = UriUtils.toUri(url,
                UriUtils.UriFeature.DEFAULT_SCHEME_HTTP,
                UriUtils.UriFeature.USE_PUNYCODED_HOSTNAME
        );
        return uri2.toUriString();
    }

    public static Common.ApplicationInfo toApplicationInfo(WebmasterApplicationInfo applicationInfo) {
        return Common.ApplicationInfo.newBuilder()
                .setHostname(applicationInfo.getHostName())
                .setName(applicationInfo.getName())
                .setStartDate(applicationInfo.getStartDate().toString())
                .setVersion(applicationInfo.getVersion())
                .build();
    }

    public static Common.MessageInfo createMessageInfo() {
        return Common.MessageInfo.newBuilder()
                .setDataTimestamp(System.currentTimeMillis())
                .build();
    }

    public static UUID proto2UUID(WebmasterCommonProto.UUID proto) {
        return new UUID(proto.getMostSignificantBits(), proto.getLeastSignificantBits());
    }

    public static WebmasterCommonProto.UUID uuid2Proto(UUID uuid) {
        return WebmasterCommonProto.UUID.newBuilder()
                .setMostSignificantBits(uuid.getMostSignificantBits())
                .setLeastSignificantBits(uuid.getLeastSignificantBits())
                .build();
    }
}
