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

import lombok.RequiredArgsConstructor;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Service;

import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.worker.client.WorkerClient;
import ru.yandex.webmaster3.core.worker.task.TaskResult;
import ru.yandex.webmaster3.core.worker.task.VerifyHostTaskData;
import ru.yandex.webmaster3.storage.verification.HostVerifierService;
import ru.yandex.webmaster3.worker.Task;

/**
 * @author avhaliullin
 */
@Category("verification")
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class VerifyHostTask extends Task<VerifyHostTaskData> {
    private final WorkerClient workerClient;
    private final HostVerifierService hostVerifierService;

    @Override
    public Result run(VerifyHostTaskData data) throws Exception {
        if (data.getNextAttempt() == null || data.getNextAttempt().isBefore(DateTime.now())) {
            hostVerifierService.verifyHost(data.getUserId(), data.getHostId(), data.getVerificationRecordId());
        } else {
            workerClient.checkedEnqueueTask(data);
        }
        return new Result(TaskResult.SUCCESS);
    }

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