library(shiny)
library(DBI)
library(RSQLite)
library(shinyjs)
library(shinyWidgets)
library(tidyverse)

source("Demographics1.R")
source("Demographics2.R")
source("Questions1_1.R")
source("Questions_Algorithm.R")
descriptxt <- read.table("Description.txt")
test_np_na_m_txt <- read.table("Scenario_np_na_m.txt")
test_np_na_i_txt <- read.table("Scenario_np_na_i.txt")
test_np_na_e_txt <- read.table("Scenario_np_na_e.txt")
test_yp_na_m_txt <- read.table("Scenario_yp_na_m.txt")
test_yp_na_i_txt <- read.table("Scenario_yp_na_i.txt")
test_yp_na_e_txt <- read.table("Scenario_yp_na_e.txt")

test_np_ya_m_txt <- read.table("Scenario_np_ya_m.txt")
test_np_ya_i_txt <- read.table("Scenario_np_ya_i.txt")
test_np_ya_e_txt <- read.table("Scenario_np_ya_e.txt")
test_yp_ya_m_txt <- read.table("Scenario_yp_ya_m.txt")
test_yp_ya_i_txt <- read.table("Scenario_yp_ya_i.txt")
test_yp_ya_e_txt <- read.table("Scenario_yp_ya_e.txt")
algorithm_yp_txt <- read.table("Algorithm_yp.txt")
algorithm_np_txt <- read.table("Algorithm_np.txt")

consenttxt <- read.table("Informed_Consent.txt")


# --- Define UI -------
ui <- navbarPage(
  # id = "Tabflow",
  "Jury Perception of Trial Information, Presentation, and Demonstrative Evidence",
  tags$head(
    tags$link(rel = "stylesheet", type = "text/css", href = "app.css"),
    HTML("<script>
  // Initialize the agent at application startup.
  const fpPromise = import('https://openfpcdn.io/fingerprintjs/v3')
    .then(FingerprintJS => FingerprintJS.load())

  // Get the visitor identifier when you need it.
  fpPromise
    .then(fp => fp.get())
    .then(result => {
      // This is the visitor identifier:
      const visitorId = result.visitorId
      console.log(visitorId)
      Shiny.setInputValue('fingerprint', visitorId);
    })
    .catch(error => console.error(error))</script>")
  ),
  useShinyjs(),
  selected="Study",
  tabPanel("Study",
  ######################## Informed Consent ###################################

  conditionalPanel(
    condition = ("input.page0==0"),
    value = "consent", fluidRow(
      column(
        width = 8, offset = 2,
        wellPanel(
          h1("Informed Consent"),
          br(),
          p(htmlOutput("infconsent")),
          br(),
          actionButton("page0", "I agree", class = "center")
        )
      )
    )
  ),
  ############################# Progress Bar ##################################
  conditionalPanel(
    condition = ("input.page2==1"),
    panel(progressBar(id="progress", value=0, total=100, display_pct=TRUE)),
  ),


  ########################  Demographic Information #############################
  conditionalPanel(
    condition = ("input.page0==1 && input.page1==0"),
    value = "demo1", fluidRow(
      column(
        width = 8, offset = 2,
        wellPanel(
          demo1,
          actionButton("page1", "Next", class = "center")
        )
      )
    )
  ),
  conditionalPanel(
    condition = ("input.page1==1 && input.page2==0"),
    value = "demo2", fluidRow(
      column(
        width = 8, offset = 2,
        wellPanel(
          demo2,
          actionButton("page2", "Next", class = "center")
        )
      )
    )
  ),

  ################ Basic Description (Used in all Scenarios) #####################

  conditionalPanel(
    condition = ("input.page2==1 && input.page3<3"),
    value = "description", fluidRow(
      column(
        width = 8, offset = 2,
        wellPanel(
          h1("Description"),
          br(),
          p(htmlOutput("descript")),
          style = "font-size:20px;",
          br(),
          actionButton("page3", "Next", class = "center")
        )
      )
    )
  ),

  ############### Scenario 1-6 Testimony - No Algorithm #######################

  conditionalPanel(
    condition = ("input.page3==3 && input.page4<7 && output.sn<7"),
    value = "scenario1", fluidRow(
      column(
        width = 8, offset = 2,
        wellPanel(
          h1("Testimony"), # should center differently
          br(),
          p(htmlOutput("test1")),
          style = "font-size:20px;",
          br(),
          actionButton("page4", "Next", class = "center")
        )
      )
    )
  ),

  ############### Scenario 7-12 Testimony - Algorithm #######################

  conditionalPanel(
    condition = ("input.page3==3 && input.page7<10 && output.sn>6"),
    value = "scenario2_1", fluidRow(
      column(
        width = 8, offset = 2,
        wellPanel(
          h1("Testimony"), # should center differently
          br(),
          p(htmlOutput("test2")),
          style = "font-size:20px;",
          br(),
          actionButton("page7", "Next", class = "center")
        )
      )
    )
  ),
  conditionalPanel(
    condition = ("input.page7==10 && input.page10<6"),
    value = "scenario2_2", fluidRow(
      column(
        width = 8, offset = 2,
        wellPanel(
          h1("Testimony"), # should center differently
          br(),
          p(htmlOutput("algorithm_test")),
          style = "font-size:20px;",
          br(),
          actionButton("page10", "Next", class = "center")
        )
      )
    )
  ),
  ################### No Algorithm Questions ####################################

  conditionalPanel(
    condition = ("input.page4==7 && input.page4_33==0"),
    value = "ques1_3", fluidRow(
      column(
        width = 8, offset = 2,
        wellPanel(
          quest1_3,
          actionButton("page4_33", "Next", class = "center")
        )
      )
    )
  ),
  conditionalPanel(
    condition = ("input.page4_33==1 && input.page4_66==0"),
    value = "ques1_3", fluidRow(
      column(
        width = 8, offset = 2,
        wellPanel(
          quest1_4,
          actionButton("page4_66", "Next", class = "center")
        )
      )
    )
  ),
    conditionalPanel(
    condition = ("input.page4_66==1 && input.page5==0"),
    value = "ques1_1", fluidRow(
      column(
        width = 8, offset = 2,
        wellPanel(
          quest1_1,
          actionButton("page5", "Next", class = "center")
        )
      )
    )
  ),
  conditionalPanel(
    condition = ("input.page5==1 && input.page6==0"),
    value = "ques1_2", fluidRow(
      column(
        width = 8, offset = 2,
        wellPanel(
          quest1_2,
          actionButton("page6", "Submit", class = "center")
        )
      )
    )
  ),

  ################### Algorithm Questions ####################################

  conditionalPanel(
    condition = ("input.page10==6 && input.page7_33==0"),
    value = "ques2_3", fluidRow(
      column(
        width = 8, offset = 2,
        wellPanel(
          quest2_3,
          actionButton("page7_33", "Next", class = "center")
        )
      )
    )
  ),
  conditionalPanel(
    condition = ("input.page7_33==1 && input.page7_66==0"),
    value = "ques2_4", fluidRow(
      column(
        width = 8, offset = 2,
        wellPanel(
          quest2_4,
          actionButton("page7_66", "Next", class = "center")
        )
      )
    )
  ),
   conditionalPanel(
    condition = ("input.page7_66==1 && input.page8==0"),
    value = "ques2_1", fluidRow(
      column(
        width = 8, offset = 2,
        wellPanel(
          quest2_1,
          actionButton("page8", "Next", class = "center")
        )
      )
    )
  ),
  conditionalPanel(
    condition = ("input.page8==1 && input.page9==0"),
    value = "ques1_2", fluidRow(
      column(
        width = 8, offset = 2,
        wellPanel(
          quest2_2,
          actionButton("page9", "Submit", class = "center")
        )
      )
    )
  ),
  ######################## Adding Completion Code ###############################
  conditionalPanel(
    condition=("input.page9==1 | input.page6==1"),
    value="confirmation", fluidRow(
      column(
        width=8, offset=2,
        wellPanel(
          h1("Completion Code: ")
        )
      )
    )
  ),

  ########################## Adding a Notepad ###################################

  conditionalPanel(
    condition = ("input.page6==0 && input.page9==0 && input.page2==1"),
    textAreaInput("Notepad", label = "Take Case Notes Here", width = "1000px", height = "500px", value = "")
  )
  )
)


###################### Define server logic #####################################
# remotes::install_github("rstudio/pool")
library(pool)


# Saving Results - commented out to work quickly on adding scenarios

# pool <- dbPool(drv = RSQLite::SQLite(), dbname = "survey_db")

# --- server ------
server <- function(input, output, session) {
  output$infconsent <- renderUI({
    HTML(consenttxt[1, ])
  })

  validate_input_list <- function(x, vars) {
    list_of_needs <- purrr::map_lgl(vars, ~ !is.null(x[[.]]))
    all(list_of_needs)
  }

  # btn_status <- function(btnid, vars) {
  #   # Trying to validate for button - does not work
  #   observe({
  #     page1_filled <- validate_input_list(input, vars)
  #     # print(paste0(btnid, " filled in = ", page1_filled))
  #     if (!page1_filled) {
  #       shinyjs::disable(id = btnid)
  #     } else {
  #       shinyjs::enable(id = btnid)
  #     }
  #   })
  # }
  #
  # btn_status("page1", c("prolificID", "race", "gender", "age", "income",
  #                       "gunown", "guncomfort"))
  # btn_status("page2", c("educ", "vote", "poli", "arrest", "state",
  #                       "jury", "jurycrim"))
  # btn_status("page4_33", c(
  #   "guilty", "strength", "probability"
  # ))
  # btn_status("page4_66", c(
  #   "gunstrength", "gunprob"
  # ))
  # btn_status("page5", c(
  #   "check1","firetestcred", "examrel", "examsci"
  # ))
  # btn_status("page6", c(
  #   "mistakes",
  #   "firerel", "check2", "firesci", "harm",
  #   "unique"
  # ))
  # btn_status("page7_33", c(
  #   "guilty2", "strength2", "probability2"
  # ))
  # btn_status("page7_66", c(
  #   "gunstrength2", "gunprob2"
  # ))
  # btn_status("page8", c(
  #   "check12","firetestcred2", "algtestcred2", "overrel2",
  #   "examrel2", "algrel2", "examsci2","oversci2", "algsci2"
  # ))
  # btn_status("page9", c(
  #   "mistakes2", "firerel2", "check22", "firesci2", "unique2",
  #   "harm2", "comments2"
  # ))

  output$descript <- renderUI({
    HTML(descriptxt[(input$page3 + 1), ])
  })

  scenario_number <- sample(1:12, 1)
  #scenario_number<-12
  output$sn <- reactive(scenario_number)
  outputOptions(output, "sn", suspendWhenHidden = FALSE)

  ###################### No Algorithm Scenarios ################################
  if (scenario_number == 1) {
    output$test1 <- renderUI({
      HTML(test_np_na_m_txt[(input$page4 + 1), ])
    })
    nPages = 14
  }

  if (scenario_number == 2) {
    output$test1 <- renderUI({
      HTML(test_np_na_i_txt[(input$page4 + 1), ])
    })
    nPages = 14
  }

  if (scenario_number == 3) {
    output$test1 <- renderUI({
      HTML(test_np_na_e_txt[(input$page4 + 1), ])
    })
    nPages = 14
  }
  if (scenario_number == 4) {
    output$test1 <- renderUI({
      HTML(test_yp_na_m_txt[(input$page4 + 1), ])
    })
    nPages = 14
  }
  if (scenario_number == 5) {
    output$test1 <- renderUI({
      HTML(test_yp_na_i_txt[(input$page4 + 1), ])
    })
    nPages = 14
  }
  if (scenario_number == 6) {
    output$test1 <- renderUI({
      HTML(test_yp_na_e_txt[(input$page4 + 1), ])
    })
    nPages = 14
  }

  ########################## Algorithm Scenarios ###############################
  if (scenario_number == 7) {
    output$test2 <- renderUI({
      HTML(test_np_ya_m_txt[(input$page7 + 1), ])
    })
    nPages = 23
  }
  if (scenario_number == 8) {
    output$test2 <- renderUI({
      HTML(test_np_ya_i_txt[(input$page7 + 1), ])
    })
    nPages = 23
  }
  if (scenario_number == 9) {
    output$test2 <- renderUI({
      HTML(test_np_ya_e_txt[(input$page7 + 1), ])
    })
    nPages = 23
  }
  if (scenario_number == 10) {
    output$test2 <- renderUI({
      HTML(test_yp_ya_m_txt[(input$page7 + 1), ])
    })
    nPages = 23
  }
  if (scenario_number == 11) {
    output$test2 <- renderUI({
      HTML(test_yp_ya_i_txt[(input$page7 + 1), ])
    })
    nPages = 23
  }
  if (scenario_number == 12) {
    output$test2 <- renderUI({
      HTML(test_yp_ya_e_txt[(input$page7 + 1), ])
    })
    nPages = 23
  }
  if (scenario_number < 10 && scenario_number > 6) {
    output$algorithm_test <- renderUI({
      HTML(algorithm_np_txt[(input$page10 + 1), ])
    })
  }
  if (scenario_number > 9) {
    output$algorithm_test <- renderUI({
      HTML(algorithm_yp_txt[(input$page10 + 1), ])
    })
  }


  # demographics 1
  Demo1Ans <- reactive({
    return(data.frame(
      prolificID = input$prolificID,
      fingerprint = input$fingerprint,
      race = paste(input$race, collapse = ", "),
      gender = input$gender, age = input$age, income = input$income, gunown = input$gunown,
      guncomfort = input$guncomfort, time = Sys.time()
    ))
  })

  observeEvent(input$page1, {
    print(isolate(input$fingerprint))
    # dbWriteTable(demodb, "demographics1", Demo1Ans(), append = TRUE)
    # dbAppendTable(pool, "demographics1", Demo1Ans())
  })

  # demographics 2
  Demo2Ans <- reactive({
    return(data.frame(
      prolificID = input$prolificID,
      fingerprint = input$fingerprint,
      educ = input$educ,
      vote = input$vote, poli = input$poli, arrest = input$arrest, state = input$state,
      jury = input$jury, jurycrim = input$jurycrim, time = Sys.time()
    ))
  })

  observeEvent(input$page2, {
    # dbWriteTable(demodb, "demographics2", Demo2Ans(), append = TRUE)
    # dbAppendTable(pool, "demographics2", Demo2Ans())
  })

  # Implementing a Page Counter
  pg_count <- 0
  page_counter <- reactiveVal(0)
  observeEvent(input$page3, {
    page_counter(page_counter() + 1)
  })
  observeEvent(input$page4, {
    page_counter(page_counter() + 1)
  })
  observeEvent(input$page7, {
    page_counter(page_counter() + 1)
  })
  observeEvent(input$page10, {
    page_counter(page_counter() + 1)
  })
  observeEvent(input$page5, {
    page_counter(page_counter() + 1)
  })
  observeEvent(input$page6, {
    page_counter(page_counter() + 1)
  })
  observeEvent(input$page8, {
    page_counter(page_counter() + 1)
  })
  observeEvent(input$page9, {
    page_counter(page_counter() + 1)
  })
  observeEvent(input$page7_33, {
    page_counter(page_counter() + 1)
  })
  observeEvent(input$page7_66, {
    page_counter(page_counter() + 1)
  })
  observeEvent(input$page4_33, {
    page_counter(page_counter() + 1)
  })
  observeEvent(input$page4_66, {
    page_counter(page_counter() + 1)
  })

  ### Progress Bar Attempt
  observe({
    updateProgressBar(session, "progress", value=page_counter(), total=nPages)
  })

  # notepad attempt
  notes <- reactive({
    return(data.frame(
      fingerprint = input$fingerprint,
      page_count = page_counter(),
      notes = input$Notepad,
      time = Sys.time()
    ))
  })

  observeEvent(page_counter(), {
    pg_count <- page_counter()
    if (pg_count > 0) {
      # dbWriteTable(demodb, "notepad_record", notes(), append = TRUE)
      # dbAppendTable(pool, "notepad_record", notes())
    }
  })


  # results for the first case
  if (scenario_number < 7) {
    Questions1_1 <- reactive({
      return(data.frame(
        fingerprint = input$fingerprint,
        guilty = input$guilty,
        strength = input$strength,
        gunstrength = input$gunstrength,
        probability = input$probability,
        gunprob = input$gunprob,
        check1 = input$check1,
        firetestcred = input$firetestcred, examrel = input$examrel,
        examsci = input$examsci,
        expunder = input$expunder,
        mistakes = input$mistakes, firerel = input$firerel,
        check2 = input$check2,
        firesci = input$firesci, harm = input$harm,
        comments = input$comments,
        unique = input$unique, time = Sys.time(),
        scenario_number = scenario_number
      ))
    })

    observeEvent(input$page6, {
      # dbWriteTable(demodb, "noalg_results", Questions1_1(), append = TRUE)
      # dbAppendTable(pool, "noalg_results", Questions1_1())
    })
  }

  # results for the second case
  if (scenario_number > 6) {
    Questions1_2 <- reactive({
      return(data.frame(
        fingerprint = input$fingerprint,
        guilty = input$guilty2,
        strength = input$strength2,
        gunstrength = input$gunstrength2,
        probability = input$probability2,
        gunprob = input$gunprob2,
        check1 = input$check12,
        firetestcred = input$firetestcred2,
        algtestcred = input$algtestcred2,
        overrel = input$overrel2,
        examrel = input$examrel2,
        algrel = input$algrel2,
        examsci = input$examsci2,
        oversci = input$oversci2,
        algsci = input$algsci2,
        expunder = input$expunder2,
        algunder = input$algunder2,

        mistakes = input$mistakes2,
        firerel = input$firerel2,
        check2 = input$check22,
        firesci = input$firesci2,
        unique = input$unique2,
        harm = input$harm2,
        comments = input$comments2,
        time = Sys.time(),
        scenario_number = scenario_number
      ))
    })

    observeEvent(input$page9, {
      # dbWriteTable(demodb, "alg_results", Questions1_2(), append = TRUE)
      # dbAppendTable(pool, "alg_results", Questions1_2())
    })


  }

}

# Run the application
shinyApp(ui = ui, server = server)
