package ru.yandex.webmaster3.worker.user.takeout;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import ru.yandex.webmaster3.core.user.takeout.UserTakeoutRequestType;
import ru.yandex.webmaster3.core.worker.task.TaskResult;
import ru.yandex.webmaster3.core.worker.task.UserTakeoutTaskData;
import ru.yandex.webmaster3.storage.user.service.UserTakeoutService;
import ru.yandex.webmaster3.worker.Task;

/**
 * @author leonidrom
 */
public class UserTakeoutTask extends Task<UserTakeoutTaskData> {
    private static final Logger log = LoggerFactory.getLogger(UserTakeoutTask.class);

    private UserTakeoutService userTakeoutService;

    @Override
    public Result run(UserTakeoutTaskData data) throws Exception {
        log.info("Processing takeout request {}", data.getRequestId());

        if (data.getRequestType() == UserTakeoutRequestType.GET) {
            userTakeoutService.processGetRequest(data.getRequestId(), data.getUserId());
        } else if (data.getRequestType() == UserTakeoutRequestType.DELETE) {
            try {
                userTakeoutService.processDeleteRequest(data.getRequestId(), data.getUserId());
            } catch (Exception e) {
                log.error("Failed to delete user data for {}", data.getRequestId(), e);
                userTakeoutService.markRequestAsFailed(data.getRequestId());
            }
        }

        return new Result(TaskResult.SUCCESS);
    }

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

    @Required
    public void setUserTakeoutService(UserTakeoutService userTakeoutService) {
        this.userTakeoutService = userTakeoutService;
    }
}
