package ru.yandex.webmaster3.worker.mirrors;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.web.util.UriComponentsBuilder;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.storage.mirrors.data.MirrorActionEnum;
import ru.yandex.webmaster3.storage.mirrors.data.MirrorRequest;

/**
 * @author akhazhoyan 02/2018
 */
class MirrorServiceRequest {
    private final Action action;
    private final String host;
    private final String main;

    MirrorServiceRequest(Action action, String host, String main) {
        this.action = Preconditions.checkNotNull(action, "'action' field is required");
        this.host = Preconditions.checkNotNull(host, "'host' field is required");
        this.main = main;
        if (action == Action.MOVE) {
            Preconditions.checkNotNull(main, "'main' field is required for move action");
        }
    }

    @VisibleForTesting
    String toUriString(String baseUri) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUri)
                .queryParam("action", action.name().toLowerCase());
        switch(action) {
            case SPLIT:
                return builder.queryParam("host", host)
                              .build().toUriString();
            case MOVE:
                return builder.queryParam("host", host)
                              .queryParam("main", main)
                              .build().toUriString();
            default:
                throw new IllegalStateException("Unexpected MirrorActionEnum value: " + String.valueOf(action));
        }
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    static MirrorServiceRequest fromMirrorRequest(MirrorRequest req) {
        WebmasterHostId hostId = req.getHostId();
        WebmasterHostId mainHostId = req.getNewMainMirrorHostId();
        return new MirrorServiceRequest(
                Action.fromMirrorActionEnum(req.getAction()),
                hostId == null ? null : IdUtils.hostIdToUrl(hostId),
                mainHostId == null ? null : IdUtils.hostIdToUrl(mainHostId)
        );
    }

    enum Action {
        SPLIT, MOVE;

        static Action fromMirrorActionEnum(MirrorActionEnum action) {
            Preconditions.checkNotNull(action);
            switch (action) {
                case UNSTICK: return SPLIT;
                default:
                    return Action.valueOf(action.name());
            }
        }
    }
}
