package com.urbancode.air.plugin.test.mstest

class UnitTestResult {
    def testName
    def className
    def testResult
    def testDuration
    def messages

    final millisPerSecond = 1000
    final millisPerMinute = 60 * millisPerSecond
    final millisPerHour = 60 * millisPerMinute

    final SUCCESS = "success"
    final FAILURE = "failure"
    final ERROR = "error"

    def testResultMap = [
            'Error': ERROR,
            'Failed': FAILURE,
            'Timeout': FAILURE,
            'Aborted': FAILURE,
            'Inconclusive': FAILURE,
            'PassedButRunAborted': SUCCESS,
            'NotRunnable': ERROR,
            'NotExecuted': FAILURE,
            'Disconnected': ERROR,
            'Warning': SUCCESS,
            'Passed': SUCCESS,
            'Completed': SUCCESS,
            'InProgress': ERROR,
            'Pending': ERROR]

    public UnitTestResult(def testName, def className, def testResult, def testDuration, def messages) {
        this.testName = testName
        this.className = getClassName(className)
        this.testResult = testResultMap[testResult]
        this.testDuration = toTestDuration(testDuration)
        this.messages = messages
    }

    def toTestDuration(msTestDuration) {
        def result = msTestDuration
        if (msTestDuration instanceof String) {
            def matcher = msTestDuration =~ /(\d+):(\d+):(\d+(?:.\d+)?)/
            def hours = matcher[0][1]
            def minutes = matcher[0][2]
            def seconds = matcher[0][3]
            def duration = hours.toInteger() * millisPerHour +
                    minutes.toInteger() * millisPerMinute +
                    seconds.toBigDecimal() * millisPerSecond
            result = duration.setScale(0, java.math.RoundingMode.HALF_UP)
        }
        return result
    }

    def getClassName(classStrongName) {
        def i = classStrongName.indexOf(',')
        def className = classStrongName[0 ..< i].trim()
        className = className.replaceAll(/\+/, '.')
        className = className.replaceAll('\\\\\\\\', '\\\\')
        return className
    }

}
