package ru.yandex.webmaster3.worker.host.verification;

import org.joda.time.Duration;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.util.RetryUtils;
import ru.yandex.webmaster3.core.worker.task.SyncVerificationStateTaskData;
import ru.yandex.webmaster3.core.worker.task.TaskResult;
import ru.yandex.webmaster3.worker.Task;
import ru.yandex.webmaster3.worker.oldwmc.OldWmcVerificationsService;

/**
 * @author avhaliullin
 */
@Category("verification")
public class SyncVerificationStateTask extends Task<SyncVerificationStateTaskData> {
    private OldWmcVerificationsService oldWmcVerificationsService;

    @Override
    public Result run(SyncVerificationStateTaskData data) throws Exception {
        try {
            RetryUtils.execute(RetryUtils.linearBackoff(5, Duration.standardMinutes(2)), () -> {
                oldWmcVerificationsService.syncVerificationState(data.getUserId(), data.getHostId());
            });
        } catch (InterruptedException e) {
            throw new WebmasterException("Failed to sync verification state",
                    new WebmasterErrorResponse.InternalUnknownErrorResponse(getClass(), null), e);
        }
        return new Result(TaskResult.SUCCESS);
    }

    @Override
    public Class<SyncVerificationStateTaskData> getDataClass() {
        return SyncVerificationStateTaskData.class;
    }

    @Required
    public void setOldWmcVerificationsService(OldWmcVerificationsService oldWmcVerificationsService) {
        this.oldWmcVerificationsService = oldWmcVerificationsService;
    }
}
