package ru.yandex.autotests.direct.commander;

import ru.yandex.qatools.allure.Allure;
import ru.yandex.qatools.allure.events.StepCanceledEvent;
import ru.yandex.qatools.allure.events.StepFailureEvent;
import ru.yandex.qatools.allure.events.StepFinishedEvent;
import ru.yandex.qatools.allure.events.StepStartedEvent;

/**
 * Created by alexey-n on 10.12.14.
 */
public class StepHelper {

    private Allure lifecycle;

    private static int counter = 0;
    private static int errorCounter = 0;
    private static boolean hasError = false;
    private static ErrorType errorType = null;

    StepHelper(Allure allureLifecycle) {
        lifecycle = allureLifecycle;
    }

    public void start(String stepName, String stepTitle) {
        StepStartedEvent event = new StepStartedEvent(stepName);
        if (!"".equals(stepTitle)) {
            event.withTitle(stepTitle);
        }
        lifecycle.fire(event);
        counter++;
    }

    public void finish() {
        if (hasError && counter == errorCounter) {
            switch (errorType) {
                case FAILED:
                    failed(null);
                    break;
                case CANCEL:
                    cancel(null);
                    break;
                case BROKEN:
                    broken(null);
                    break;
            }
        }
        lifecycle.fire(new StepFinishedEvent());
        counter--;
    }

    public void cancel(String message) {
        StepCanceledEvent event = new StepCanceledEvent();
        if (message != null) {
            event.setThrowable(new Throwable(message));
        }
        lifecycle.fire(event);
        errorCounter = counter - 1;
        hasError = true;
        errorType = ErrorType.CANCEL;
    }

    public void broken(String message) {
        StepFailureEvent event = new StepFailureEvent();
        if (message != null) {
            event.setThrowable(new Throwable(message));
        }
        lifecycle.fire(event);
        errorCounter = counter - 1;
        hasError = true;
        errorType = ErrorType.BROKEN;
    }

    public void failed(String message) {
        StepFailureEvent event = new StepFailureEvent();
        if (message != null) {
            event.setThrowable(new AssertionError(message));
        } else {
            event.setThrowable(new AssertionError());
        }
        lifecycle.fire(event);
        errorCounter = counter - 1;
        hasError = true;
        errorType = ErrorType.FAILED;
    }

    public static void init() {
        StepHelper.counter = 0;
        StepHelper.errorCounter = 0;
        StepHelper.hasError = false;
        StepHelper.errorType = null;
    }
}
