function(input, output, session) {
  update_busy_bar(100)
  loggedUser <- reactiveVal()
    #Set variable for user session
  i18n <- Translator$new(translation_csvs_path = paste0(d_, a_$i18n$path), separator_csv="|")
  active_ui_lang <- grep("ui",i18n$get_languages(), invert = TRUE, value = TRUE)
  clog('Good time!')

#1. UPDATE SELECTED LANGUAGE, INCLUDING ON LOAD---- 
  observe({
    langSet <- a_$i18n$lang
    query <- parseQueryString(session$clientData$url_search)
    if (!is.null(query[['lang']])) {
      if (query[['lang']] %in% active_ui_lang) {
        langSet <- query[['lang']]
      }
    }
    shiny.i18n::update_lang(langSet, session)
    i18n$set_translation_language(langSet)
  })
  
  observeEvent(input$switch_lang, {
    if (i18n$get_translation_language() == 'en') {
      langSet <- 'km'
    } else {
      langSet <- 'en'
    }
    shiny.i18n::update_lang(langSet, session)
    i18n$set_translation_language(langSet)
    shinyjs::runjs(paste0('document.getElementById("lang_image").src="', i18n$get_translation_language(), '.jpg";'))
  })
  
  observeEvent(input$open_login, {
    if (length(loggedUser())>0) {return()}
    showModal(modalDialog(tags$head(tags$style(".modal-dialog{ width:300px}")),
                          fluidPage(
                            fluidRow(textInput('userName', label=i18n$t('ui_user_login'))),
                            fluidRow(textInput('password', label=i18n$t('ui_password')))
                          ),
                          easyClose = TRUE,
                          footer = tagList(
                            span(actionButton('loginAct', i18n$t('ui_login')), style='position: absolute; left: 16px;'), modalButton("Close"))
    ), session = getDefaultReactiveDomain())
  })

  
  observeEvent(input$loginAct, {
    # password function digest::digest('icem2025',algo = 'sha256', serialize = FALSE)
    clog('Start logging in!')
      if (nchar(input$userName)*nchar(input$password)==0) {
        return()
      } else {
        userlogin <- gsub("'","-",input$userName)
        db.query <- dbSendQuery(conn, sprintf("SELECT * FROM %s.capfishui_user WHERE username='%s';", a_$database$schema, userlogin))
        userlogin<- dbFetch(db.query, n=1)
        pssw <- input$password
        if (digest::digest(pssw,algo = 'sha256', serialize = FALSE)==userlogin$password_hash) {
          shinyjs::alert(paste0('Logged in as ', userlogin$description))
          userlogin$province <- stri_split(userlogin$province,fixed =',')
          loggedUser(userlogin)
          db.query <- dbSendQuery(conn, sprintf("UPDATE %s.capfishui_user SET last_login = NOW() WHERE username='%s';", a_$database$schema, userlogin$username))
        } else {
          shinyjs::alert("Not log in, invalid username or password")
          #session$reload()
        }
        removeModal(session = getDefaultReactiveDomain())
      }
  })

  observe({
    print(loggedUser())
    if (length(loggedUser())==0) {return()}
    if (length(loggedUser()$province[[1]])==1) {
      shinyjs::runjs(paste0('document.getElementById("prov_sum_title").innerHTML="',i18n$t('ui_metric_summary'),': ', i18n$t(loggedUser()$province[[1]]),'";'))
      #output$showProv <- renderUI({tags$h4(i18n$t(loggedUser()))})
    } else {
      output$showProv <- renderUI({selectInput('selectProv', label = NULL,  width = "200px", choices = setNames(loggedUser()$province[[1]], i18n$t(loggedUser()$province[[1]])))})
    }
  })
  
  observeEvent(input$selectProv, {
    print(input$selectProv)
  })
  
  output$home_html <- renderText(includeHTML(paste0(w_,sprintf(a_$html$home, i18n$get_translation_language()))))
  # observeEvent(input$navpage, {
  #   if(input$navpage == '<span class="i18n" data-key="ui_nav_page_nbs">Nature-based Solutions</span>'){
  #     print('NbS')
  #     output$nbs_html <- renderText(includeHTML(paste0(w_,sprintf(a_$html$nbs, i18n$get_translation_language()))))
  #   } else if(input$navpage == '<span class="i18n" data-key="ui_nav_page_map">Atlas Map Viewer</span>'){
  #     print('Atlas Map Viewer')
  #   } else if(input$navpage == '<span class="i18n" data-key="ui_nav_page_gallery">Atlas Map Gallery</span>'){
  #     print('Atlas Gallery')
  #     output$gallery_html <- renderText(includeHTML(paste0(w_,sprintf(a_$html$gallery, i18n$get_translation_language()))))
  #   } else if(input$navpage == '<span class="i18n" data-key="ui_nav_page_doc">Document</span>'){
  #     print('Document')
  #     output$doc_html <- renderText(includeHTML(paste0(w_,sprintf(a_$html$docs, i18n$get_translation_language()))))
  #   }
  # })
  ### Check geoserver if it's used
  # for (gs in a_$gs[names(a_$gs_)=='url']) {
  #   tryCatch({
  #     resp <- GET(url = paste0(gs, "rest/workspaces/", a_$gs_$ws))
  #     print(resp)
  #     if (resp$status_code == 200) {
  #       geoserver_url <- gs
  #       break
  #     }
  #   }, error = function(e) {print(e)})
  # }
  output$map <- renderLeaflet({
    leaflet(options = leafletOptions(zoomDelta = 0.25, zoomSnap = 0.25,  minZoom =7 , maxZoom=18)) %>%
      addProviderTiles("CartoDB", group = "Carto") %>%
      addProviderTiles( "OpenStreetMap",group = "Open Street Map", options = providerTileOptions(zIndex = -20)) %>%
      addProviderTiles("Stamen.Toner",group = "Stamen Toner", options = providerTileOptions(zIndex = -20)) %>%
      addProviderTiles("Stamen.Terrain",group = "Stamen Terrain", options = providerTileOptions(zIndex = -20)) %>%
      addProviderTiles("Esri.WorldStreetMap",group = "Esri World Street Map", options = providerTileOptions(zIndex = -20)) %>%
      addProviderTiles("Esri.WorldImagery",group = "Esri World Imagery", options = providerTileOptions(zIndex = -20)) %>%
      # add Titles surface water body
      addTiles(
        urlTemplate = "https://tiles.maps.eox.at/wmts/1.0.0/hydrography_3857/default/g/{z}/{y}/{x}.jpg",
        attribution = 'Hydrography overlay { Data © OpenStreetMap contributors, Rendering © EOX }',
        options = tileOptions(
          noWrap = TRUE,
          continuousWorld = TRUE,
          tms = FALSE,
          tileSize = 256,
          zIndex = 30),
        group = "Waterbodies",
        layerId = "Waterbodiesl"
      ) %>%
      addLayersControl(
        baseGroups = c("Carto",
                       "Open Street Map", "Stamen Toner",
                       "Stamen Terrain", "Esri World Street Map",  "Esri World Imagery"),
        overlayGroups = c( "Waterbodies"),position = c("topleft"), options = layersControlOptions(collapsed = TRUE, autoZIndex = FALSE)
      )%>%
      hideGroup("Waterbodies") %>%
      leafem::addMouseCoordinates()%>%
      addMeasure(primaryLengthUnit = "kilometers",
                 primaryAreaUnit = "hectares", position = c("topleft")) %>%
      setMaxBounds(lng1 = 101, lat1 = 8, lng2 = 111, lat2 = 17) %>%
      setView(lng = 105.2, lat = 12.4, zoom = 8) %>%
      addControl(actionButton("clearall", title="Clear all layers", icon ("broom")),position="topleft")%>%
      addScaleBar(position = c("topleft")) 
  })
   observeEvent(input$sel_layer5,{
     ib <- input$sel_layer5
     if(ib != 0){
       output$legend_SuitabilityRC <- renderText(paste0('<br> Estimated suitability for river cages <br> (0 = low, 100 = high) ',html_legend_Suitability))
       leafletProxy('map') %>%
         addRasterImage(r1, colors = pal, opacity = 0.8, group = 'raster1', maxBytes = 4 * 1024 * 1024)
     } else {
       leafletProxy('map') %>% clearGroup("raster1")
       output$legend_SuitabilityRC<- renderText({c('')})
     }
   })
   observeEvent(input$sel_layer6,{
     ib <- input$sel_layer6
     if(ib != 0){
       output$legend_SuitabilityEP <- renderText(paste0('<br> Estimated suitability for earth ponds <br> (0 = low, 100 = high) ',html_legend_Suitability))
       leafletProxy('map') %>%
         addRasterImage(r2, colors = pal, opacity = 0.8, group = 'raster2', maxBytes = 4 * 1024 * 1024)
     } else {
       leafletProxy('map') %>% clearGroup("raster2")
       output$legend_SuitabilityEP<- renderText({c('')})
     }
   })
}
