package ru.yandex.webmaster3.internal.user.host;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

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.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.user.UserVerifiedHost;
import ru.yandex.webmaster3.internal.common.InternalAction;
import ru.yandex.webmaster3.internal.common.security.ActionInternalGrant;
import ru.yandex.webmaster3.internal.common.security.InternalGrant;
import ru.yandex.webmaster3.storage.user.dao.VerifiedHostsYDao;

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;

/**
 * @author kravchenko99
 */
@ReadAction
@Description("batch версия: Получить список сайтов, подтвержденных пользователем")
@Component("/user/host/batchListUserHosts")
@ActionInternalGrant(InternalGrant.USER_HOST)
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class BatchListUserHostsAction extends InternalAction<BatchListUserHostsRequest, BatchListUserHostsResponse> {

    private final VerifiedHostsYDao verifiedHostsYDao;

    @Override
    public BatchListUserHostsResponse process(BatchListUserHostsRequest request) throws WebmasterException {
        Stream<Pair<Long, UserVerifiedHost>> userVerifiedHosts = verifiedHostsYDao.batchListHosts(request.getUserIds()).stream();

        if (!request.isShowInvisible()) {
            userVerifiedHosts = userVerifiedHosts.filter(uh -> uh.getValue().getVerificationType().isDisplayable());
        }

        final Map<Long, List<VerifiedHost>> verifiedHostsByUser = userVerifiedHosts
                .collect(groupingBy(Pair::getLeft, mapping(x -> toVerifiedHost(x.getRight()), toList())));

        final List<BatchListUserHostsResponse.UserVerifiedHosts> userInfos = request.getUserIds().stream().map(userId ->
                new BatchListUserHostsResponse.UserVerifiedHosts(userId, verifiedHostsByUser.getOrDefault(userId, Collections.emptyList())))
                .collect(Collectors.toList());
        return new BatchListUserHostsResponse(userInfos);
    }

    private VerifiedHost toVerifiedHost(UserVerifiedHost userVerifiedHost) {
        return new VerifiedHost(userVerifiedHost.getWebmasterHostId(), userVerifiedHost.getVerificationDate().toInstant());
    }
}
