package ru.yandex.webmaster3.viewer.http.host.feedback;

import java.util.ArrayList;
import java.util.List;

import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.data.WebmasterUser;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.user.UserVerifiedHost;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.storage.user.UserUnverifiedHost;
import ru.yandex.webmaster3.storage.user.service.UserHostsService;
import ru.yandex.webmaster3.storage.util.HostListTreeBuilder;
import ru.yandex.webmaster3.viewer.http.AbstractUserAction;

/**
 * @author avhaliullin
 */
@ReadAction
@Category("verification")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Component("/internal/api/feedbackHostsAddedByUser")
public class FeedbackUserAddedHostsAction extends AbstractUserAction<FeedbackUserAddedHostsRequest, FeedbackUserAddedHostsResponse> {
    private final UserHostsService userHostsService;
    private final HostListTreeBuilder hostListTreeBuilder;

    @Override
    public FeedbackUserAddedHostsResponse process(FeedbackUserAddedHostsRequest request) {
        WebmasterUser user = request.getWebmasterUser();
        List<UserVerifiedHost> verifiedHosts = userHostsService.getVerifiedHosts(user);
        List<UserUnverifiedHost> unverifiedHosts = userHostsService.getMayBeUnverifiedHosts(user);

        List<WebmasterHostId> pinnedHosts = userHostsService.getPinnedHosts(user);

        Pair<List<HostListTreeBuilder.HostTreeNode>, HostListTreeBuilder.HostCounters> treeResults =
                hostListTreeBuilder.createHostTree(verifiedHosts, unverifiedHosts, pinnedHosts);
        List<FeedbackUserAddedHostsResponse.Host> result = new ArrayList<>();
        for (HostListTreeBuilder.HostTreeNode node : treeResults.getLeft()) {
            addNode(true, node, result);
        }
        return new FeedbackUserAddedHostsResponse(result);
    }

    private static void addNode(boolean isMainMirror, HostListTreeBuilder.HostTreeNode node, List<FeedbackUserAddedHostsResponse.Host> result) {
        if (node.isAdded()) {
            result.add(new FeedbackUserAddedHostsResponse.Host(
                    node.getHostId(),
                    IdUtils.toHostString(node.getHostId(), false, false, false),
                    IdUtils.toHostString(node.getHostId(), false, true, false),
                    node.isVerified(),
                    isMainMirror
            ));
        }
        for (HostListTreeBuilder.HostTreeNode child : node.getChildren()) {
            addNode(false, child, result);
        }
    }
}
