package ru.yandex.webmaster3.core.worker.task;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.http.WebmasterJsonModule;

/**
 * Обертка над WorkerTaskData для передачи в ручку EnqueueTasksAction
 *
 * @author Oleg Bazdyrev
 */
public class WorkerTaskDataWrapper {

    private static final ObjectMapper OM = new ObjectMapper()
            .registerModules(new JodaModule(), new WebmasterJsonModule(false));

    private WorkerTaskType taskType;
    private String taskId;
    private String taskData;
    private WorkerTaskPriority taskPriority = WorkerTaskPriority.NORMAL;

    public WorkerTaskDataWrapper() {
    }

    @JsonCreator
    public WorkerTaskDataWrapper(
            @JsonProperty("taskType") WorkerTaskType taskType,
            @JsonProperty("taskId") String taskId,
            @JsonProperty("taskData") String taskData,
            @JsonProperty("taskPriority") WorkerTaskPriority taskPriority) {
        this.taskType = taskType;
        this.taskId = taskId;
        this.taskData = taskData;
        this.taskPriority = taskPriority;
    }

    public static WorkerTaskDataWrapper fromWorkerTaskData(WorkerTaskData wtd) {
        try {
            return new WorkerTaskDataWrapper(wtd.getTaskType(), wtd.getTaskId().toString(), OM.writeValueAsString(wtd),
                    wtd.getTaskPriority());
        } catch (JsonProcessingException e) {
            throw new WebmasterException("Serializing error", new WebmasterErrorResponse.UnableToReadJsonRequestResponse(null, e), e);
        }
    }

    public WorkerTaskType getTaskType() {
        return taskType;
    }

    public void setTaskType(WorkerTaskType taskType) {
        this.taskType = taskType;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public String getTaskData() {
        return taskData;
    }

    public void setTaskData(String taskData) {
        this.taskData = taskData;
    }

    public WorkerTaskPriority getTaskPriority() {
        return taskPriority;
    }

    public void setTaskPriority(WorkerTaskPriority taskPriority) {
        this.taskPriority = taskPriority;
    }
}
