package ru.yandex.webmaster3.api.verification.action;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.api.http.auth.ActionPermission;
import ru.yandex.webmaster3.api.http.auth.Permission;
import ru.yandex.webmaster3.api.http.rest.AbstractApiAction;
import ru.yandex.webmaster3.api.verification.data.ApiUserVerifiedHost;
import ru.yandex.webmaster3.api.verification.data.ApiVerificationType;
import ru.yandex.webmaster3.core.blackbox.service.BlackboxUsersService;
import ru.yandex.webmaster3.core.host.verification.UinUtil;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.user.UserVerifiedHost;
import ru.yandex.webmaster3.storage.user.service.UserHostsService;

/**
 * @author avhaliullin
 */
@Description("Посмотреть пользователей, подтвердивших права на сайт")
@Category("verification")
@Component
@ActionPermission(Permission.COMMON)
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class UsersVerifiedHostAction extends AbstractApiAction<UsersVerifiedHostRequest, UsersVerifiedHostResponse> {

    private final BlackboxUsersService blackboxExternalYandexUsersService;
    private final UserHostsService userHostsService;

    @Override
    public UsersVerifiedHostResponse process(UsersVerifiedHostRequest request) {
        Map<Long, UserVerifiedHost> users = userHostsService.listUsersVerifiedHost(request.getHostId());

        Map<Long, String> uid2Login = blackboxExternalYandexUsersService.mapUserIdsToLogins(users.keySet());

        List<ApiUserVerifiedHost> result = new ArrayList<>();
        for (Map.Entry<Long, UserVerifiedHost> entry : users.entrySet()) {
            long uid = entry.getKey();
            UserVerifiedHost verificationInfo = entry.getValue();
            if (verificationInfo.getVerificationType().isDisplayable()) {
                if (uid2Login.containsKey(uid)) {
                    ApiVerificationType verificationType = ApiVerificationType.fromVerificationType(
                            verificationInfo.getVerificationType()
                    );
                    result.add(new ApiUserVerifiedHost(
                            uid2Login.get(uid),
                            UinUtil.getUinString(verificationInfo.getVerificationUin()),
                            verificationType,
                            verificationInfo.getVerificationDate()
                    ));
                }
            }
        }
        Collections.sort(result, Comparator.comparing(ApiUserVerifiedHost::getVerificationDate));
        return new UsersVerifiedHostResponse(result);
    }
}
