package ru.yandex.wmconsole.servantlet.api;

import java.util.List;

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.wmconsole.authorization.ApiOAuthPermission;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.data.info.UsersHostsInfo;
import ru.yandex.wmconsole.data.info.api.ApiUsersHostsInfo;
import ru.yandex.wmconsole.data.wrappers.api.ApiUsersHostsInfoWrapper;
import ru.yandex.wmconsole.error.ClientException;
import ru.yandex.wmconsole.error.ClientProblem;
import ru.yandex.wmconsole.verification.VerificationTypeEnum;
import ru.yandex.wmtools.common.error.InternalException;

/**
 * @author ailyin
 */
public class ApiVerifyHostInfoServantlet extends AbstractApiServantlet {
    @Override
    public void apiDoProcess(ServRequest req, ServResponse res, long userId) throws ClientException, InternalException {

            BriefHostInfo hostInfo = getHostInfoAndCheckHostAdded(req, userId);
            UsersHostsInfo usersHostsInfo = getUsersHostsService().getUsersHostsInfo(userId, hostInfo.getId());
            if (usersHostsInfo == null) {
                throw new ClientException(ClientProblem.HOST_NOT_OWNED_BY_USER, "Host is not added to the users host list");
            }
            //todo use another query (without join)
            List<UsersHostsInfo> verifiedList = getUsersHostsService().listVerifiedUsersForHost(hostInfo.getId());
            boolean otherUsersExist = false;
            for (UsersHostsInfo info : verifiedList) {
                if ((info.getUserId() != userId) && !VerificationTypeEnum.CHEAT.equals(info.getVerificationType())) {
                    otherUsersExist = true;
                }
            }

            ApiUsersHostsInfo info = new ApiUsersHostsInfo(usersHostsInfo.getHostName(),
                    usersHostsInfo.getVerificationType(), usersHostsInfo.getVerificationState(),
                    usersHostsInfo.getVerificationDate(), usersHostsInfo.getVerificationUin(), otherUsersExist);

            res.addData(new ApiUsersHostsInfoWrapper(info));
    }

    @Override
    public ApiOAuthPermission getRequiredPermission() {
        return ApiOAuthPermission.COMMON_OPERATIONS;
    }
}
