# Module UI
  
#' @title   mod_autenticacao_ui and mod_autenticacao_server
#' @description  A shiny Module.
#'
#' @param id shiny id
#' @param input internal
#' @param output internal
#' @param session internal
#'
#' @rdname mod_autenticacao
#'
#' @keywords internal
#' @export 
#' @importFrom shiny NS tagList 
mod_autenticacao_ui <- function(id){
  ns <- NS(id)
}
    
# Module Server
    
#' @rdname mod_autenticacao
#' @export
#' @keywords internal
    
mod_autenticacao_server <- function(input, output, session, login, logon_info){
  logwriter <- get_log_writer('farmview')
  ns <- session$ns
  
   ## ao encerrar a sessão salva dados de usuário senão for nullo
  shiny::onSessionEnded(function(){
    tout <- get_date_time()
    #browser()
    if(isolate(login[['permissao']]) == T && !is.null(isolate(logon_info[['usuario']])) ){
      write.table(isolate({
        list(
          franquia = ifelse(is.null(logon_info$usuario$franquia), "", logon_info$usuario$franquia), 
          id_franquia = ifelse(is.null(logon_info$usuario$id_franquia), "", logon_info$usuario$id_franquia), 
          email = ifelse(is.null(logon_info$usuario$email),"",logon_info$usuario$email),
          logindate = logon_info$login$data, logintime = logon_info$login$hora,
          logoutdate = tout$data, logouttime = tout$hora
        )
      }), file=paste0("log/farmview",format(Sys.Date(), "%Y"),".csv"), append = T, col.names = F, row.names=F, sep=";")
      
    }
  })
 
  go_login <- function(redirect_url, session){
    
    if(session$clientData$url_port != "") {
      port <- paste0(":", session$clientData$url_port)
    } else {
      port <- ""
    }
    
    redirect_url <- paste0(session$clientData$url_protocol, "//", session$clientData$url_hostname, port, session$clientData$url_pathname)
    
    runjs(
      paste0('window.location.replace("https://inttegra.com/sistema/sistema.htm?l=login&redirect_uri=',redirect_url,'");')
    )  
  }
  
  get_url <- function(url,token){
    # set_config(config(ssl_verifypeer = 0L))
    return(content(GET(url = url,add_headers(Authorization =  paste0("Bearer ",token))),as = 'text'))
  }
  
  get_user <- function(token){
    get_url(url='https://www.inttegra.com/api/usuario',token=token)
  }
  
  AuthCode <- function(session){
    pars <- parseQueryString(session$clientData$url_search)
    if(length(pars$token) > 0){
      return(pars$token)
    }
  }
  
  observeEvent(session, {
    AuthCode(session) -> token
    if(!login$permissao){
      if(is.null(token)){
        go_login("farmview", session)
      } else {
        
        tryCatch({
          usuario<-fromJSON(system(paste('curl -k -H "Authorization: bearer', token,'" https://www.inttegra.com/api/usuario'),intern=T))
          
        },error=function(e){
          runjs(paste("alert('","Erro ao buscar dados do usuário. Contacte o desenvolvedor.","')"))
          stopApp()
        })
        
        if(!is.null(usuario$nome)){
          login[['permissao']] <- T
          logon_info[['usuario']] <- usuario
         
          #########
          logon_info[['login']] <- get_date_time()
        }
      }
    } else {
      logon_info[['usuario']] <- list(id_franquia="622",nome='Luigi', franquia="TERRA", tipo_usuario = 'U') #1076 DSM
      logon_info[['login']] <- get_date_time()
    }
    
  })
  
}
    
## To be copied in the UI
# mod_autenticacao_ui("autenticacao_ui_1")
    
## To be copied in the server
# callModule(mod_autenticacao_server, "autenticacao_ui_1")
 
