package ru.yandex.wmconsole.verification;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.wmconsole.data.VerificationStateEnum;
import ru.yandex.wmconsole.data.info.UsersHostsInfo;
import ru.yandex.wmconsole.service.DelegationsService;
import ru.yandex.wmtools.common.error.InternalException;

/**
 * @author baton
 */
public class DelegationVerifier extends ConsistentVerifier {
    private static final Logger log = LoggerFactory.getLogger(DelegationVerifier.class);

    private DelegationsService delegationsService;

    @Override
    public UsersHostsInfo verify(UsersHostsInfo verInfo) {
        try {
            Long delegationId = delegationsService.getDelegationForHostAndUser(verInfo.getHostId(), verInfo.getUserId());
            if (delegationId != null) {
                return UsersHostsInfo.createVerifiedNow(verInfo, VerificationTypeEnum.DELEGATION);
            } else {
                return UsersHostsInfo.createNotVerifiedNow(verInfo, VerificationStateEnum.UNKNOWN);
            }
        } catch (InternalException e) {
            log.error("Error while searching delegations in DB", e);
            return UsersHostsInfo.createNotVerifiedNow(verInfo, VerificationStateEnum.UNKNOWN);
        }
    }

    @Required
    public void setDelegationsService(DelegationsService delegationsService) {
        this.delegationsService = delegationsService;
    }
}
