package ru.yandex.webmaster3.worker.turbo;

import java.util.UUID;

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

import ru.yandex.webmaster3.core.worker.task.PeriodicTaskState;
import ru.yandex.webmaster3.core.worker.task.PeriodicTaskType;
import ru.yandex.webmaster3.storage.turbo.dao.adv.TurboAdvBlockPostponedYDao;
import ru.yandex.webmaster3.storage.turbo.service.adv.TurboAutoAdvService;
import ru.yandex.webmaster3.worker.PeriodicTask;
import ru.yandex.webmaster3.worker.TaskSchedule;

/**
 * ishalaru
 * 08.09.2020
 **/
@Service
@AllArgsConstructor(onConstructor_ = {@Autowired})
public class PostponedAdvCreationTask extends PeriodicTask<PostponedAdvCreationTask.State> {
    private final TurboAutoAdvService turboAutoAdvService;
    private final TurboAdvBlockPostponedYDao turboAdvBlockPostponedYDao;

    @Override
    public Result run(UUID runId) throws Exception {
        turboAdvBlockPostponedYDao.executeForAll(s -> {
            if (s.getEndDate().isAfter(DateTime.now())) {
                tryCreate(s);
            } else {
                turboAutoAdvService.resetStatus(s.getDomain());
            }
        });
        return Result.SUCCESS;
    }

    private void tryCreate(TurboAdvBlockPostponedYDao.AdvPostponedInfo advPostponedInfo) {
        switch (advPostponedInfo.getStatus()) {
            case USER_CREATE_RSI_ACCOUNT:
                checkUserAccount(advPostponedInfo);
                break;
            case WAITING_DOMAIN_VALIDATION:
                tryCreateDomain(advPostponedInfo);
                break;
            case WAITING_EXTERNAL_USER_APPROVE:
                break;
        }

    }

    public void checkUserAccount(TurboAdvBlockPostponedYDao.AdvPostponedInfo advPostponedInfo) {
        if (turboAutoAdvService.userIsExists(Long.valueOf(advPostponedInfo.getData().getUserId()))) {
            turboAutoAdvService.initTurboAutoAdvBlocks(advPostponedInfo.getData().getUserId(), advPostponedInfo.getDomain());
        }
    }

    public void tryCreateDomain(TurboAdvBlockPostponedYDao.AdvPostponedInfo advPostponedInfo) {
        turboAutoAdvService.createAdvAfterDomainValidation(advPostponedInfo);
    }

    @Override
    public PeriodicTaskType getType() {
        return PeriodicTaskType.TURBO_ADV_POSTPONED_CREATION;
    }

    @Override
    public TaskSchedule getSchedule() {
        return TaskSchedule.startByCron("0 30 0/3 * * *");
    }

    public static class State implements PeriodicTaskState {

    }
}
