#!groovy
@Library('infraLib') _

def buildInfo
def buildDescription
def buildDisplayName
def devicesList = apolloGoHelpers.supportedMobileDevices()
def lastBuild

def buildStep(targetJobName, appTargetJobName, lastBuild, iosDeviceVersion, numberOfParallelTests, uiTests, artist, marker, resultsBuildNumber) {
  build wait: false,
    job: targetJobName,
    parameters: [
      booleanParam(name: 'USE_CACHE', value: true),
      string(name: 'TARGET_JOB_NAME', value: appTargetJobName),
      string(name: 'TARGET_BUILD_NUMBER', value: "${lastBuild.getNumber()}"),
      string(name: 'IOS_BUILD', value: "${lastBuild.getNumber()}"),
      string(name: 'IOS_DEVICE_VERSION', value: "${iosDeviceVersion}"),
      string(name: 'APPIUM_VERSION', value: '1.22.0'),
      string(name: 'NUMBER_OF_PARALLEL_TESTS', value: "${numberOfParallelTests}"),
      string(name: 'UI_TESTS', value: "${uiTests}"),
      string(name: 'PREVIOUS_ALLURE_RESULTS_BUILD_NUMBER', value: "${resultsBuildNumber}"),
      string(name: 'ARTIST', value: "${artist}"),
      string(name: 'MARKER', value: "${marker}")
    ]
}

pipeline {
  agent none

  options {
    buildDiscarder logRotator(artifactDaysToKeepStr: '',
                              artifactNumToKeepStr: '',
                              daysToKeepStr: '',
                              numToKeepStr: '5')
    disableResume()
    ansiColor('xterm')
  }

  parameters {
    separator(name: 'rti-wrapper-build-params', sectionHeader: 'Build parameters')
    listGitBranches(
      branchFilter: '.*',
      credentialsId: 'theorchard-ci-ssh-key',
      defaultValue: 'refs/heads/development',
      name: 'RTI_BRANCH',
      quickFilterEnabled: true,
      remoteURL: 'git@github.com:theorchard/ama-frontend.git',
      selectedValue: 'DEFAULT',
      sortMode: 'NONE',
      tagFilter: '*',
      type: 'PT_BRANCH_TAG'
    )
    choice(
      choices: [
        'IOS_BUILD_DEV',
        'IOS_BUILD_PROD',
        'Please make a choice',
        'ANDROID_BUILD',
        'IOS_SIMULATOR_BUILD_DEV',
        'IOS_SIMULATOR_BUILD_PROD',
      ],
      name: 'FORCE',
      description: 'Force a build.'
    )
    separator(name: 'rti-wrapper-test-params', sectionHeader: 'Test parameters')
    listGitBranches(
      branchFilter: '.*',
      credentialsId: 'theorchard-ci-ssh-key',
      defaultValue: 'refs/heads/master',
      name: 'RTI_MOBILE_AUTO_BRANCH',
      quickFilterEnabled: true,
      remoteURL: 'git@github.com:theorchard/rti-mobile-automation.git',
      selectedValue: 'DEFAULT',
      sortMode: 'NONE',
      tagFilter: '*',
      type: 'PT_BRANCH_TAG'
    )
    choice(
      choices: devicesList,
      description: 'Choose a device',
      name: 'IOS_DEVICE_VERSION'
    )
    choice(
      choices: [
        '5',
        '4',
        '3',
        '2',
        '1',
        '6', // we have been given additional 5 executors
        '7',
        '8',
        '9',
        '10'
      ],
      description: 'Choose a device',
      name: 'NUMBER_OF_PARALLEL_TESTS'
    )
    string (
      defaultValue: '1.22.0',
      description: 'Version of Appium to use',
      name: 'APPIUM_VERSION',
      trim: true
    )
    string (
      defaultValue: '',
      description: 'Limit check to these UI tests only',
      name: 'UI_TESTS',
      trim: true
    )
    string (
      defaultValue: '',
      description: 'Copy allure report from this build',
      name: 'PREVIOUS_ALLURE_RESULTS_BUILD_NUMBER',
      trim: true
    )
    string (
      defaultValue: '',
      description: 'Artist',
      name: 'ARTIST',
      trim: true
    )
    choice(
      choices: [
        'ALL',
        'smoke',
        'regression',
        'artist',
      ],
      description: 'Choose set of tests',
      name: 'MARKER'
    )
  }

  environment {
    APP_BRANCH_OR_TAG    = "${params.RTI_BRANCH.minus('refs/heads/')}".replace('/', '%2F')
    TEST_BRANCH_OR_TAG   = "${params.RTI_MOBILE_AUTO_BRANCH.minus('refs/heads/')}".replace('/', '%2F')
    APP_TARGET_JOB_NAME  = "RTI/pipelines/ama-frontend/${env.APP_BRANCH_OR_TAG}"
    TEST_TARGET_JOB_NAME = "RTI/pipelines/rti-mobile-automation/${env.TEST_BRANCH_OR_TAG}"
  }

  stages {
    stage('Build Info') {
      steps {
        script {
          currentBuild.description = """branches: ${env.APP_BRANCH_OR_TAG}/${env.TEST_BRANCH_OR_TAG}
isAndroidBuild = ${params.FORCE == 'ANDROID_BUILD'}
isiOSBuildDev = ${params.FORCE == 'IOS_BUILD_DEV'}
isiOSBuildProd = ${params.FORCE == 'IOS_BUILD_PROD'}
isiOSSimulatorBuildDev = ${params.FORCE == 'IOS_SIMULATOR_BUILD_DEV'}
isiOSSimulatorBuildProd = ${params.FORCE == 'IOS_SIMULATOR_BUILD_PROD'}
"""
        } /** end: script */
      } /** end: steps */
    } /** end: stage */
    stage('Build FE') {
      steps {
        script {
          // we don't need to build artifact each time in order to test it
          // check if latest build has the same properties
          lastBuild = Jenkins.instance.getItemByFullName(env.APP_TARGET_JOB_NAME).getLastSuccessfulBuild()
          parametersAction = lastBuild.getAction(hudson.model.ParametersAction)

          // skip build if has the same properties
          if (parametersAction.getParameter("FORCE_BUILD").getValue() != params.FORCE) {
            lastBuild = build job: env.APP_TARGET_JOB_NAME,
              parameters: [
                booleanParam(name: 'FORCE_PUBLISH', value: false),
                string(name: 'FORCE_BUILD', value: params.FORCE)
              ]
          } /** end: if */
        } /** end: script */
      } /** end: steps */
    } /** env: stage */
    stage('Run tests') {
      steps {
        script {
          if (params.ARTIST == '') {
            buildStep(env.TEST_TARGET_JOB_NAME,
              env.APP_TARGET_JOB_NAME,
              lastBuild,
              params.IOS_DEVICE_VERSION,
              params.NUMBER_OF_PARALLEL_TESTS,
              params.UI_TESTS,
              params.ARTIST,
              params.MARKER,
              params.PREVIOUS_ALLURE_RESULTS_BUILD_NUMBER)
          } else {
            values = "${params.ARTIST}".split(',')
            for (value in values) {
              buildStep(env.TEST_TARGET_JOB_NAME,
                env.APP_TARGET_JOB_NAME,
                lastBuild,
                params.IOS_DEVICE_VERSION,
                params.NUMBER_OF_PARALLEL_TESTS,
                params.UI_TESTS,
                value,
                params.MARKER,
                params.PREVIOUS_ALLURE_RESULTS_BUILD_NUMBER)
            }
          }
        } /** end: script */
      } /** end: steps */
    } /** end: stage */
  } /** end: stages */
} /** end: pipeline */
