package com.freeleaps.devops

import com.freeleaps.devops.enums.CodeLinterTypes
import com.freeleaps.devops.lint.Linter
import com.freeleaps.devops.lint.PyLint
import com.freeleaps.devops.lint.ESLint

class CodeLintExecutor {
  def steps
  def workspace
  def configs
  def linterType
  def component

  CodeLintExecutor(steps, workspace, configs, linterType, component) {
    this.steps = steps
    this.workspace = workspace
    this.configs = configs
    this.linterType = linterType
    this.component = component
  }

  def execute() {
    if (configs == null || configs.isEmpty()) {
      steps.log.warn("CodeLintExecutor", "Not set configurations file, using default configurations as fallback")
      def configFilePath
      switch (linterType) {
        case CodeLinterTypes.PYLINT:
          configFilePath = "com/freeleaps/devops/builtins/lint/pylint/pylintrc"
          break
        case CodeLinterTypes.ESLINT:
          configFilePath = "com/freeleaps/devops/builtins/lint/eslint/eslintrc.js"
          break
        default:
          steps.log.error("CodeLintExecutor", "Unknown linter type")
          return
      }
      steps.writeFile file: "${workspace}.lintconfig", text: steps.libraryResource(configFilePath)
      configs = "${workspace}.lintconfig"
    }

    Linter linter
    switch (linterType) {
      case CodeLinterTypes.PYLINT:
        linter = new PyLint(steps, workspace, configs)
        break
      case CodeLinterTypes.ESLINT:
        if (component.eslintVersion == null || component.eslintVersion.isEmpty()) {
          steps.log.error("CodeLintExecutor", "ESLint version is required")
          return
        }
        linter = new ESLint(steps, workspace, configs, component.eslintVersion, component.eslintPlugins)
        break
      default:
        steps.log.error("CodeLintExecutor", "Unknown linter type")
        return
    }
    linter.lint()
  }
}