package ru.yandex.wmtools.common.util.scheduler.journal;

import org.springframework.beans.factory.annotation.Required;
import ru.yandex.common.scheduler.Journal;
import ru.yandex.common.scheduler.JournalReader;
import ru.yandex.common.scheduler.model.TaskDescriptor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author avhaliullin
 */
public class CompositJournal implements Journal {
    private List<Journal> journals = new ArrayList<Journal>();
    private int feedbackJournal = 0;

    @Required
    public void setJournals(List<Journal> journals) {
        this.journals = journals;
    }

    public void setFeedbackJournal(int feedbackJournal) {
        this.feedbackJournal = feedbackJournal;
    }

    @Override
    public JournalReader getJournalReader() {
        if (journals.size() <= feedbackJournal) {
            return null;
        }
        return journals.get(feedbackJournal).getJournalReader();
    }

    @Override
    public long taskStarted(long userId, TaskDescriptor task) {
        long res = -1;
        int counter = 0;
        for (Journal journal : journals) {
            long ans = journal.taskStarted(userId, task);
            if (feedbackJournal == counter++) {
                res = ans;
            }
        }
        return res;
    }

    @Override
    public void taskFailed(long runId, TaskDescriptor task, String message) {
        for (Journal journal : journals) {
            journal.taskFailed(runId, task, message);
        }
    }

    @Override
    public void taskFinished(long runId, TaskDescriptor task, String message) {
        for (Journal journal : journals) {
            journal.taskFinished(runId, task, message);
        }
    }

    @Override
    public void taskEvent(long runId, TaskDescriptor task, String message) {
        for (Journal journal : journals) {
            journal.taskEvent(runId, task, message);
        }
    }
}
