package ru.yandex.wmtools.common.sita;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;

/**
 * User: azakharov
 * Date: 18.03.14
 * Time: 12:51
 */
public class SitaMirroringJsonRequest {

    private static final Logger log = LoggerFactory.getLogger(SitaMirroringJsonRequest.class);

    private static final ObjectMapper OM = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);

    public static String toJson(final SitaMirroringRequest sitaUrlFetchRequest, final String sitaProxyUserName) throws IOException {
        String json = OM.writeValueAsString(toRequest(sitaUrlFetchRequest, sitaProxyUserName));
        log.debug("Sita request: {}", json);
        return json;
    }

    private static SitaJson.TRequest toRequest(final SitaMirroringRequest sitaMirroringRequest, String sitaProxyUserName) {
        SitaJson.TRequest request = new SitaJson.TRequest();

        request.AuthInfo = new SitaJson.TAuthInfo();
        request.AuthInfo.User = sitaProxyUserName;

        SitaJson.TActionData actionData = new SitaJson.TActionData();
        request.Data = new SitaJson.TActionData[]{actionData};
        actionData.Url = sitaMirroringRequest.getUri().toASCIIString();

        SitaJson.TAction action = new SitaJson.TAction();
        request.Actions = new SitaJson.TAction[]{action};

        action.Type = SitaJson.EActionType.AT_MIRRORING;

        action.MirroringData = new SitaJson.TMirroringData();

        if (sitaMirroringRequest.getAction() != null) {
            switch(sitaMirroringRequest.getAction()) {
                case RERANK: action.MirroringData.Action = SitaJson.EMirroringAction.RERANK; break;
                case STICK: action.MirroringData.Action = SitaJson.EMirroringAction.STICK; break;
                case UNSTICK: action.MirroringData.Action = SitaJson.EMirroringAction.UNSTICK; break;
                default: action.MirroringData.Action = null;
            }
        }

        if (sitaMirroringRequest.getNewMainMirror() != null) {
            action.MirroringData.NewMainHost = sitaMirroringRequest.getNewMainMirror().toASCIIString();
        } else if (sitaMirroringRequest.getHosts() != null) {
            action.MirroringData.Hosts = new String[sitaMirroringRequest.getHosts().size()];
            int i = 0;
            for (URI host : sitaMirroringRequest.getHosts()) {
                action.MirroringData.Hosts[i] = host.toASCIIString();
                i++;
            }
        }

        request.Settings = new SitaJson.TSettings();
        request.Settings.UrlValidator = SitaJson.EUrlValidator.ROBOT_URL_VALIDATOR;

        return request;
    }
}
