import SessionCommand from "../utils/SessionCommand"
import * as fs from "fs"
import * as path from "path"
import * as prompts from "prompts"
import { translateExercise } from "../utils/rigoActions"
import SessionManager from "../managers/session"
import Console from "../utils/console"
import { saveTranslatedReadme } from "../utils/creatorUtilities"

// This function list the names of the exercise directories inside the ./exercises folder, if the exercises folder doesn't exist, it will look for the ./.learn/exercises folder
const listExercises = async () => {
  const exercisesDir = path.join(process.cwd(), "exercises")
  const learnExercisesDir = path.join(process.cwd(), ".learn", "exercises")

  const exercises = fs.readdirSync(exercisesDir).filter(file => {
    return fs.statSync(path.join(exercisesDir, file)).isDirectory()
  })

  if (exercises.length > 0) {
    return exercises
  }

  return fs.readdirSync(learnExercisesDir).filter(file => {
    return fs.statSync(path.join(learnExercisesDir, file)).isDirectory()
  })
}

const getReadmeForExercise = async (exercise: string) => {
  const readmePath = path.join(
    process.cwd(),
    "exercises",
    exercise,
    "README.md"
  )
  return fs.readFileSync(readmePath, "utf8")
}

export default class BuildCommand extends SessionCommand {
  static description =
    "List all the lessons, the user is able of select many of them to translate to the given languages"

  async init() {
    const { flags } = this.parse(BuildCommand)
    await this.initSession(flags)
  }

  async run() {
    const { flags } = this.parse(BuildCommand)

    const exercises = await listExercises()

    const exercisesToTranslate = await prompts([
      {
        type: "multiselect",
        name: "exercises",
        message: "Select the exercises to translate",
        choices: exercises.map(exercise => ({
          title: exercise,
          value: exercise,
        })),
      },
      {
        type: "text",
        name: "output_language",
        message:
          "Write the languages to translate to comma separated. Example: English, Spanish, French",
        initial: "Spanish",
      },
    ])

    const configObject = this.configManager?.get()

    if (configObject) {
      // build exerises
      Console.debug("Building exercises")
      this.configManager?.buildIndex()
    }

    let sessionPayload = await SessionManager.getPayload()
    if (!sessionPayload || !sessionPayload.rigobot) {
      Console.error("You must be logged in to upload a LearnPack package")
      try {
        sessionPayload = await SessionManager.login()
      } catch (error) {
        Console.error("Error trying to authenticate")
        Console.error((error as TypeError).message || (error as string))
      }
    }

    const rigoToken = sessionPayload.rigobot.key

    await Promise.all(
      exercisesToTranslate.exercises.map(async (exercise: string) => {
        await Promise.all(
          exercisesToTranslate.output_language
            .split(",")
            .map(async (language: string) => {
              const readme = await getReadmeForExercise(exercise)
              const response = await translateExercise(
                rigoToken,
                {
                  text_to_translate: readme,
                  output_language: language,
                },
                `${process.env.HOST}/webhooks/translate-exercise`
              )

              await saveTranslatedReadme(
                exercise,
                response.parsed.output_language_code,
                response.parsed.translation
              )
              Console.success(
                `Translated ${exercise} to ${language} successfully`
              )
            })
        )
      })
    )

    this.exit(0)
  }
}
