#!groovy

import groovy.json.JsonOutput
import java.util.Optional
import hudson.tasks.test.AbstractTestResultAction
import hudson.model.Actionable
import hudson.tasks.junit.CaseResult

def slackNotificationChannel = "build"
def author = ""
def message = ""
def testSummary = ""
def total = 0
def failed = 0
def skipped = 0

def notifySlack(text, channel, attachments) {
    def slackURL = 'https://hooks.slack.com/services/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'
    def jenkinsIcon = 'https://wiki.jenkins-ci.org/download/attachments/2916393/logo.png'

    def payload = JsonOutput.toJson([text: text,
        channel: channel,
        username: "AI",
        icon_url: jenkinsIcon,
        attachments: attachments
    ])

    sh "curl -X POST --data-urlencode \'payload=${payload}\' ${slackURL}"
}

def getGitAuthor = {
    def commit = sh(returnStdout: true, script: 'git rev-parse HEAD')
    author = sh(returnStdout: true, script: "git --no-pager show -s --format='%an' ${commit}").trim()
}

def getLastCommitMessage = {
    message = sh(returnStdout: true, script: 'git log -1 --pretty=%B').trim()
}

def populateGlobalVariables = {
    getLastCommitMessage()
    getGitAuthor()
}

node {
    try {
        stage('Checkout') {
            checkout scm
        }
        
        stage ('Integration Tests') {
            env.NODEJS_HOME = "${tool 'recent node'}"
            env.PATH="${env.NODEJS_HOME}/bin:${env.PATH}"
           
           sh 'npm --version'           
           populateGlobalVariables
            //sh 'npm install newman --global'

            try{
            	sh 'npm --prefix integration_tests/ run engine-test-dev'
                currentBuild.result = 'SUCCESS'
                def buildColor = currentBuild.result == null ? "good" : "warning"
                def buildStatus = currentBuild.result == null ? "Success" : currentBuild.result
                def jobName = "${env.JOB_NAME}"
                jobName = jobName.getAt(0..(jobName.indexOf('/') - 1))
                notifySlack("", slackNotificationChannel, [
                    [
                        title: "Integration Tests for ${jobName}, build #${env.BUILD_NUMBER}",
                        title_link: "${env.BUILD_URL}",
                        color: "${buildColor}",
                        author_name: "${author}",
                        text: "${buildStatus}\n${author}",
                        fields: [
                            [
                                title: "Last Commit",
                                value: "${message}",
                                short: false
                            ]
                        ]
                    ]
                ])
            } catch(Exception e){
                notifySlack("", slackNotificationChannel, [
                    [
                        title: "Integration Tests for ${jobName}, build #${env.BUILD_NUMBER}",
                        title_link: "${env.BUILD_URL}",
                        color: "${buildColor}",
                        text: "${buildStatus}\n${author}",
                        "mrkdwn_in": ["fields"],
                        fields: [
                            [
                                title: "Last Commit",
                                value: "${message}",
                                short: false
                            ],
                            [
                                title: "Error",
                                value: "${e}",
                                short: false
                            ]
                        ]
                    ]
                ])
            }
            junit 'integration_tests/newman.xml'

        }   
   
        
    } catch (hudson.AbortException ae) {
        // ignored
    } catch (e) {
        def buildStatus = "Failed"

        notifySlack("", slackNotificationChannel, [
            [
                title: "${env.JOB_NAME}, build #${env.BUILD_NUMBER}",
                title_link: "${env.BUILD_URL}",
                color: "danger",
                author_name: "${author}",
                text: "${buildStatus}",
                fields: [
                    [
                        title: "Branch",
                        value: "${env.GIT_BRANCH}",
                        short: true
                    ],
                    [
                        title: "Last Commit",
                        value: "${message}",
                        short: false
                    ],
                    [
                        title: "Error",
                        value: "${e}",
                        short: false
                    ]
                ]
            ]
        ])

        throw e
    }
}