package ru.yandex.webmaster3.core.blackbox.service;

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

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.TreeTraversingParser;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpRequest;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.yandex.webmaster3.core.blackbox.UserWithLogin;

/**
 * @author aherman
 */
public class SessionIdRequest extends BlackboxRequest<UserWithLogin> {
    private static final Logger log = LoggerFactory.getLogger(SessionIdRequest.class);

    private final String sessionId;
    private final String sslSessionId;
    private final String userIp;
    private final String host;

    public SessionIdRequest(String sessionId, String sslSessionId, String userIp, String host) {
        this.sessionId = sessionId;
        this.sslSessionId = sslSessionId;
        this.userIp = userIp;
        this.host = host;
    }

    public String getSessionId() {
        return sessionId;
    }

    public String getSslSessionId() {
        return sslSessionId;
    }

    public String getUserIp() {
        return userIp;
    }

    public String getHost() {
        return host;
    }

    @Override
    HttpUriRequest createRequest(URIBuilder uriBuilder) throws URISyntaxException {
        uriBuilder = uriBuilder
                .setParameter("method", "sessionid")
                .setParameter("sessionid", sessionId)
                .setParameter("host", host)
                .setParameter("userip", userIp);

        if (!StringUtils.isEmpty(sslSessionId)) {
            uriBuilder = uriBuilder.setParameter("sslsessionid", sslSessionId);
        }

        URI uri = uriBuilder.build();
        log.info("URI: {}", uri);
        return new HttpGet(uri);
    }

    @Override
    BlackboxResponse<UserWithLogin> parseJson(JsonNode jsonNode) throws IOException {
        UidLoginHolder uidLoginHolder = OM.readValue(new TreeTraversingParser(jsonNode), UidLoginHolder.class);
        return BlackboxResponse.createData(new UserWithLogin(uidLoginHolder.uid.value, uidLoginHolder.login));
    }

    private static class UidLoginHolder {
        private final String login;
        private final UidHolder uid;

        public UidLoginHolder(@JsonProperty("login") String login, @JsonProperty("uid") UidHolder uid) {
            this.login = login;
            this.uid = uid;
        }
    }

    private static class UidHolder {
        private final long value;

        public UidHolder(@JsonProperty("value") long value) {
            this.value = value;
        }
    }
}
