package ru.yandex.wmtools.common.sita.newmirroring;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.yandex.wmtools.common.sita.SitaJson;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * @author avhaliullin
 */
public class SitaNewMirroringJsonRequest {

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

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

    public static String toJson(final SitaNewMirroringRequest 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 SitaNewMirroringRequest sitaNewMirroringRequest, 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 = sitaNewMirroringRequest.getUrl().toASCIIString();

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

        action.Type = SitaJson.EActionType.AT_NEW_MIRRORING;

        action.NewMirroringData = new SitaJson.TNewMirroringData();

        action.NewMirroringData.Action = sitaNewMirroringRequest.getAction();
        switch (sitaNewMirroringRequest.getAction()) {
            case MOVE:
                List<String> hosts = new ArrayList<>();
                for (URI uri : sitaNewMirroringRequest.getHosts()) {
                    hosts.add(uri.toASCIIString());
                }
                action.NewMirroringData.Hosts = hosts;
                break;

            case UNSTICK:
            default:
        }

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

        return request;
    }
}
