# iatgen-generated QSF Translator Shiny Web App
library(shiny)
library(tr.iatgen)

inst <- available.languages()
choices<-inst$Code
names(choices) <- inst$Description

# Compose ui.
ui <- fixedPage(titlePanel("iatgen-generated QSF Translator"),
                fileInput("qsf_file", "Upload the .qsf file generated by iatgen."),
                radioButtons("custom", "Available Translations", inline = TRUE,
                             list("Supported Languages" = "no", "Custom Translations" = "yes")),
                conditionalPanel(condition = "input.custom == 'yes'",
                                 fileInput("custom_lang_file", "Upload your translations.")),
                conditionalPanel(condition = "input.custom == 'no'",
                                 selectInput("lang", "Translate", choices)
                                 ),
                downloadButton("tr_qsf", "Download translated IAT"))

# Server function.
server <- function(input, output) {

  values <- reactiveValues(custom_lang_file=NULL)
  
  # upload custom translation file
  observeEvent(input$custom_lang_file, {
    
    if (is.null(input$custom_lang_file))
    {
      values$custom_lang_file <- NULL
      return(NULL)     
    }
    
    print(paste("loading file ",input$custom_lang_file))
    
    ret <- validate.language(input$custom_lang_file$datapath)
    if (is.null(ret)) return(NULL)
   
    values$custom_lang <- ret
    values$custom_lang_file <- input$custom_lang_file$datapath
  }) 

  # upload qsf file
  observeEvent(input$qsf_file, {
    
    if (is.null(input$qsf_file))
    {
      values$qsf_file <- NULL
      return(NULL)     
    }
    
    print(paste("loading file ",input$qsf_file))
    
    values$qsf_file <- input$qsf_file$datapath
    values$qsf_file_name <- input$qsf_file$name
  }) 

  # translate and download translation
  output$tr_qsf <- downloadHandler(
    filename = function() {
      paste("tr_", values$qsf_file_name, sep="")
    },
    content = function(file) {
      print(paste0("translating file ",values$qsf_file, " to ", input$lang, " saving into ", file))
      if (input$custom == "no") {
        result <- translate.qsf(file=values$qsf_file, lang=input$lang, dst_file=file)
      } else {
        # FIXME: check values$custom_lang_file not NULL
        result <- translate.qsf(file=values$qsf_file, lang=values$custom_lang, lang_file=values$custom_lang_file, dst_file=file)
      }
    }
  )
}

# Construct App.
shinyApp(ui, server)
