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

import ru.yandex.webmaster3.core.security.InfectedUrlData;
import ru.yandex.webmaster3.core.security.WarningUrlData;
import ru.yandex.webmaster3.proto.security.Security;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author avhaliullin
 */
public class SecurityProtoConverter {
    public static List<WarningUrlData> proto2WarningUrlSamples(Security.DefaultSamples message) {
        return message.getUrlsList().stream()
                .map(url -> new WarningUrlData(url.getUrl(), ConverterUtils.toDateTime(url.getLastCheck())))
                .collect(Collectors.toList());
    }

    public static Security.DefaultSamples warningUrlSamples2Proto(List<WarningUrlData> samples) {
        Security.DefaultSamples.Builder builder = Security.DefaultSamples.newBuilder();
        for (WarningUrlData url : samples) {
            builder.addUrlsBuilder()
                    .setUrl(url.getUrl())
                    .setLastCheck(ConverterUtils.fromDateTime(url.getLastCheck()));
        }
        return builder.build();
    }

    public static List<InfectedUrlData> proto2InfectedUrlSamples(Security.InfectedSamples message) {
        return message.getUrlsList().stream()
                .map(url ->
                        new InfectedUrlData(url.getUrl(), ConverterUtils.toDateTime(url.getLastCheck()),
                                url.hasVirusName() ? url.getVirusName() : null, url.getShowVerdict(), url.getUrlsChainList())
                )
                .collect(Collectors.toList());
    }

    public static Security.InfectedSamples infectedUrlSamples2Proto(List<InfectedUrlData> samples) {
        Security.InfectedSamples.Builder builder = Security.InfectedSamples.newBuilder();
        for (InfectedUrlData url : samples) {
            Security.InfectedUrlInfo.Builder urlBuilder = builder.addUrlsBuilder()
                    .setUrl(url.getUrl())
                    .setLastCheck(ConverterUtils.fromDateTime(url.getLastCheck()))
                    .setShowVerdict(url.isShowVerdict())
                    .addAllUrlsChain(url.getUrlsChain() == null ? Collections.emptyList() : url.getUrlsChain());
            if (url.getVirusName() != null) {
                urlBuilder.setVirusName(url.getVirusNameInternal());
            }
        }
        return builder.build();
    }

}
