package net.pagejects.allure

import net.pagejects.core.PageObjectListener
import ru.yandex.qatools.allure.Allure
import ru.yandex.qatools.allure.annotations.Step
import ru.yandex.qatools.allure.events.StepFinishedEvent
import ru.yandex.qatools.allure.events.StepStartedEvent
import java.lang.reflect.Method
import java.text.MessageFormat
import java.util.*

/**
 * This class allow to integrate Allure with Pagejects
 *
 * @author Andrey Paslavsky
 * @since 0.1
 */
class AllurePagejectsAdaptor(private val allure: Allure = Allure.LIFECYCLE) : PageObjectListener {
    override fun beforeMethod(method: Method, pageObject: Any, args: Array<out Any?>?) {
        val step = method.getAnnotation(Step::class.java)
        if (step != null) {
            val event = StepStartedEvent(method.nameWithArgs(args)).withTitle(step.title(args))
            allure.fire(event)
        }
    }

    private fun Step.title(args: Array<out Any?>?): String? = if (value.isNotBlank()) {
        if (args != null) MessageFormat.format(value, *args) else MessageFormat.format(value)
    } else {
        null
    }

    private fun Method.nameWithArgs(args: Array<out Any?>?) =
            if (args != null) name + Arrays.toString(args) else name

    override fun afterMethod(method: Method, pageObject: Any, args: Array<out Any?>?, result: Any?) {
        if (method.isAnnotationPresent(Step::class.java)) {
            allure.fire(StepFinishedEvent())
        }
    }
}