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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.regions.data.HostRegion;
import ru.yandex.webmaster3.core.regions.data.HostRegionSourceTypeEnum;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.proto.Geodata;

import java.util.*;

/**
 * @author avhaliullin
 */
public class GeodataProtoConverter {
    private static final Logger log = LoggerFactory.getLogger(GeodataProtoConverter.class);

    public static Map<WebmasterHostId, Set<HostRegion>> convert(Geodata.GeoDataMessage message) {
        List<Geodata.HostInfo> hosts = message.getHostsList();
        Map<WebmasterHostId, Set<HostRegion>> result = new HashMap<>();
        for (Geodata.HostInfo host : hosts) {
            String hostName = host.getHostname();
//            log.debug("Geodata service: hostname={}", hostName);
            WebmasterHostId hostId = IdUtils.urlToHostId(hostName);

            Set<HostRegion> regions = new HashSet<>();
            for (Geodata.AttributeInfo attr : host.getAttributesList()) {
                int regionId = attr.getRegionId();
                HostRegionSourceTypeEnum sourceType;
                switch (attr.getSourceType()) {
                    case CATALOG:
                        sourceType = HostRegionSourceTypeEnum.CATALOG;
                        break;
                    case DICTIONARY:
                        sourceType = HostRegionSourceTypeEnum.DICTIONARY;
                        break;
                    case AUTOCLASSIFIER:
                        sourceType = HostRegionSourceTypeEnum.AUTOCLASSIFIER;
                        break;
                    case WEBMASTER:
                        sourceType = HostRegionSourceTypeEnum.WEBMASTER;
                        break;
                    default:
                        continue;
                }
                if (host.getVisible() || sourceType != HostRegionSourceTypeEnum.CATALOG) {
                    regions.add(new HostRegion(regionId, sourceType));
                }
            }
            result.put(hostId, regions);
        }
        return result;
    }

}
