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

import org.springframework.beans.factory.annotation.Required;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.host.verification.UserHostVerificationInfo;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.internal.common.InternalAction;
import ru.yandex.webmaster3.internal.common.security.InternalGrant;
import ru.yandex.webmaster3.core.user.UserVerifiedHost;
import ru.yandex.webmaster3.storage.user.service.UserHostsService;
import ru.yandex.webmaster3.storage.verification.HostVerifierService;

/**
 * Created by leonidrom on 14/06/2017.
 */
@Description("Посмотреть информацию о подтверждении прав")
@ReadAction
public class HostVerificationInfoAction extends InternalAction<HostVerificationInfoRequest, HostVerificationInfoResponse> {
    private UserHostsService userHostsService;

    public HostVerificationInfoAction() {
        super(InternalGrant.HOST_VERIFICATION);
    }

    @Override
    public HostVerificationInfoResponse process(HostVerificationInfoRequest request) throws WebmasterException {
        if (request.getUserAddedHost().isVerified()) {
            UserVerifiedHost verifiedHost = userHostsService.getVerifiedHost(request.getWebmasterUser(), request.getHostId());
            return HostVerificationInfoResponse.createVerified(verifiedHost);
        }

        UserHostVerificationInfo verificationInfo =
                userHostsService.getVerificationInfo(request.getUserId(), request.getHostId());
        if (verificationInfo.getVerificationStatus() == null) {
            return HostVerificationInfoResponse.createNeverVerified(verificationInfo);
        } else if (HostVerifierService.isVerificationExpired(verificationInfo)) {
            return HostVerificationInfoResponse.createExpired(verificationInfo);
        }

        return HostVerificationInfoResponse.createNotVerified(verificationInfo);
    }

    @Required
    public void setUserHostsService(UserHostsService userHostsService) {
        this.userHostsService = userHostsService;
    }
}
