library(shiny)
library(shinythemes)
library(shinyjs)
library(dplyr)
library(ggvis)
library(plotly)

shinyUI(
  tags$html(
    tags$head(
      useShinyjs(),
      if (grepl("XP",Sys.info()['release']))
      {
        #this was added for compatibility with call to V8 library in WinXp
        #all functions from my_shinyjs_scripts.js should be added here!
        extendShinyjs(script = "www/js/my_shinyjs_scripts.js",
                      functions = c("pageCol",
                                    "selectRows",
                                    "filterTblByPositions",
                                    "changeConfirmedStatus",
                                    "toggleCatModal",
                                    "changeActiveTab"))
      }
      else
      {
        #Not WinXp
        extendShinyjs(script = "www/js/my_shinyjs_scripts.js")
      },
      includeScript("www/js/single_double_click.js"),
      includeScript("www/js/scripts.js"),
      includeCSS("www/css/styles.css")
    ),
    tags$div(
      navbarPage(
        # here add code for google analytics
        #header = includeScript("ga.js"),
        title = "rdmlEdit",
        theme = shinytheme("cerulean"),
        tabPanel("Files",
                 fluidRow(
                   column(3,
                          wellPanel(
                            fileInput("rdmlFiles",
                                      HTML("Upload <b>.RDML</b>, <b>.csv</b>, <b>.lc96p</b>, <b>.xls</b> or <b>.xlsx</b> file(s):"),
                                      multiple = TRUE),
                            selectizeInput("rdmlFileSlct",
                                           "View File",
                                           choices = "",
                                           options= list(
                                             create =TRUE
                                           )),
                            actionButton("createSubversionRDMLBtn",
                                         "Create Subversion"),
                            actionButton("removeRDMLBtn",
                                         "Remove RDML")),
                          wellPanel(
                            selectInput("mergeRdmlsSlct",
                                        "Merge RDMLs",
                                        multiple = TRUE,
                                        choices = ""),
                            actionButton("mergeBtn",
                                         "Merge")
                          )),
                   column(9,
                          fluidRow(
                            column(3,
                                   textInput("dateMadeText", "Date Made",
                                             ""),
                                   textInput("dateUpdatedText", "Date Updated",
                                             ""))),
                          plotOutput("dendroRDMLplot"))
                 )),
        navbarMenu("Metadata",
                   tabPanel("ID",
                            selectizeInput("idSlct",
                                           "Select ID",
                                           choices = "",
                                           options = list(
                                             create = TRUE
                                           )),
                            textInput("idPublisherText", "Publisher",
                                      ""),
                            textInput("idSerialNumberText", "Serial Number",
                                      ""),
                            textInput("idMD5HashText", "MD5 Hash",
                                      ""),
                            actionButton("removeIDBtn",
                                         "Remove ID")),
                   tabPanel("Experimenter",
                            selectizeInput("experimenterSlct",
                                           "Select Experimenter",
                                           choices = "",
                                           options = list(
                                             create = TRUE
                                           )),
                            
                            textInput("experimenterIdText", "ID",
                                      ""),
                            textInput("experimenterFirstNameText", "First Name",
                                      ""),
                            textInput("experimenterLastNameText", "Last Name",
                                      ""),
                            textInput("experimenterEmailText", "Email",
                                      ""),
                            textInput("experimenterLabNameText", "Lab Name",
                                      ""),
                            textInput("experimenterLabAdressText", "Lab Address",
                                      ""),
                            actionButton("removeExperimenterBtn",
                                         "Remove Experimenter")),
                   tabPanel("Documentation",
                            selectizeInput("documentationSlct",
                                           "Select Documentation",
                                           choices = "",
                                           options= list(
                                             create =TRUE
                                           )),
                            textInput("documentationIdText", "ID",
                                      ""),
                            textInput("documentationTextText", "Text",
                                      ""),
                            actionButton("removeDocumentationBtn",
                                         "Remove Documentation")),
                   tabPanel("Dye",
                            selectizeInput("dyeSlct",
                                           "Select Dye",
                                           choices = "",
                                           options= list(
                                             create =TRUE
                                           )),
                            #                           uiOutput("dyeSlct"),
                            #                           uiOutput("dyeTabWell"),
                            textInput("dyeIdText", "ID",
                                      ""),
                            textInput("dyeDescriptionText", "Text",
                                      ""),
                            actionButton("removeDyeBtn",
                                         "Remove Dye")
                            
                   ),
                   tabPanel("Sample",
                            selectizeInput("sampleSlct",
                                           "Select Sample",
                                           choices = "",
                                           options= list(
                                             create =TRUE
                                           )),
                            textInput("sampleIdText", "ID",
                                      ""),
                            textInput("sampleDescriptionText", 
                                      "Description",
                                      ""),
                            selectInput("sampleDocumentationSlct",
                                        "Documentation",
                                        multiple = TRUE,
                                        choices = ""),
                            wellPanel(selectizeInput("samplexRefSlct",
                                                     "Select xRef",
                                                     choices = "",
                                                     options= list(
                                                       create =TRUE
                                                     )),
                                      textInput("samplexRefNameText", 
                                                "xRef Name",
                                                ""),
                                      textInput("samplexRefIdText", 
                                                "xRef ID",
                                                ""),
                                      actionButton("removeSamplexRefBtn",
                                                   "Remove xRef")),
                            wellPanel(selectizeInput("sampleAnnotationSlct",
                                                     "Select Annotation",
                                                     choices = "",
                                                     options= list(
                                                       create =TRUE
                                                     )),
                                      textInput("sampleAnnotationPropertyText", 
                                                "Annotation Property",
                                                ""),
                                      textInput("sampleAnnotationValueText", 
                                                "Annotation Value",
                                                ""),
                                      actionButton("removeSampleAnnotationBtn",
                                                   "Remove Annotation")),
                            selectInput("sampleTypeSlct",
                                        "Type",
                                        choices = c("unkn", "ntc",
                                                    "nac",
                                                    "std", "ntp",
                                                    "nrt", "pos",
                                                    "opt")),
                            checkboxInput("sampleInterRunCalibratorChk",
                                          "Inter Run Calibrator",
                                          FALSE),
                            wellPanel("Quantity",
                                      textInput("sampleQuantityValueText", 
                                                "Value",
                                                ""),
                                      selectInput("sampleQuantityUnitSlct",
                                                  "Unit",
                                                  choices = c("other",
                                                              "cop", "fold",
                                                              "dil", "ng",
                                                              "nMol"))
                            ),
                            checkboxInput("sampleCalibratorSampleChk",
                                          "Calibartor Sample",
                                          FALSE),
                            wellPanel("cDNA Synthesis Method",
                                      textInput("sampleCsmEnzymeText", 
                                                "Enzyme",
                                                ""),
                                      selectInput("sampleCsmPrimingMethodSlct",
                                                  "Priming Method",
                                                  choices = c("",
                                                              "oligo-dt", "random",
                                                              "target-specific",
                                                              "oligo-dt and random",
                                                              "other")),
                                      checkboxInput("sampleCsmDnaseTreatmentChk",
                                                    "DNAase Treatment",
                                                    FALSE),
                                      selectInput("sampleCsmTccSlct",
                                                  "Thermal Cycling Conditions",
                                                  choices = "")
                            ),
                            wellPanel("Template Quantity",
                                      textInput("sampleTemplateQuantityConcText", 
                                                "Concentration",
                                                ""),
                                      selectInput("sampleTemplateQuantityNucleotideSlct",
                                                  "Nucleotide",
                                                  choices = c("",
                                                              "DNA",
                                                              "genomic DNA",
                                                              "cDNA",
                                                              "RNA"))
                            ),
                            actionButton("removeSampleBtn",
                                         "Remove Sample")),
                   tabPanel("Target",
                            selectizeInput("targetSlct",
                                           "Select Target",
                                           choices = "",
                                           options= list(
                                             create =TRUE
                                           )),
                            textInput("targetIdText", "ID",
                                      ""),
                            textInput("targetDescriptionText", 
                                      "Description",
                                      ""),
                            selectInput("targetDocumentationSlct",
                                        "Documentation",
                                        multiple = TRUE,
                                        choices = ""),
                            wellPanel(selectizeInput("targetxRefSlct",
                                                     "Select xRef",
                                                     choices = "",
                                                     options= list(
                                                       create =TRUE
                                                     )),
                                      textInput("targetxRefNameText", 
                                                "xRef Name",
                                                ""),
                                      textInput("targetxRefIdText", 
                                                "xRef ID",
                                                ""),
                                      actionButton("removetargetxRefBtn",
                                                   "Remove xRef")),
                            selectInput("targetTypeSlct",
                                        "Type",
                                        choices = c("toi",
                                                    "ref")),
                            textInput("targetAemText", 
                                      "Amplification Efficiency Method",
                                      ""),
                            textInput("targetAeText", 
                                      "Amplification Efficiency",
                                      ""),
                            textInput("targetAeSeText", 
                                      "Amplification Efficiency SE",
                                      ""),
                            textInput("targetDetectionLimitText", 
                                      "Detection Limit",
                                      ""),
                            selectInput("targetDyeIdSlct",
                                        "Dye ID",
                                        choices = ""),
                            wellPanel("Sequences",
                                      selectInput("targetSequencesTypeSlct",
                                                  "Oligo Type",
                                                  choices = c("forwardPrimer",
                                                              "reversePrimer",
                                                              "probe1",
                                                              "probe2",
                                                              "amplicon")),
                                      textInput("targetSequences3PrimeTagText", 
                                                "Tree Prime Tag",
                                                ""),
                                      textInput("targetSequences5PrimeTagText", 
                                                "Five Prime Tag",
                                                ""),
                                      textInput("targetSequencesSequenceText", 
                                                "Sequence",
                                                "")),
                            wellPanel("Commercial Assay",
                                      textInput("targetCaCompanyText", 
                                                "Company",
                                                ""),
                                      textInput("targetCaOrderNumberText", 
                                                "Order Number",
                                                "")),
                            actionButton("removeTargetBtn",
                                         "Remove target")),
                   tabPanel("Thermal Cycling Conditions",
                            selectizeInput("tccSlct",
                                           "Select Thermal Cycling Conditions",
                                           choices = "",
                                           options= list(
                                             create =TRUE
                                           )),
                            textInput("tccIdText", "ID",
                                      ""),
                            textInput("tccDescriptionText", 
                                      "Description",
                                      ""),
                            selectInput("tccDocumentationSlct",
                                        "Documentation",
                                        multiple = TRUE,
                                        choices = ""),
                            textInput("tccLidTemperatureText", 
                                      "Lid Temperature",
                                      ""),
                            selectInput("tccExperimenterSlct",
                                        "Experimenter",
                                        multiple = TRUE,
                                        choices = ""),
                            wellPanel(selectizeInput("tccStepSlct",
                                                     "Select Step",
                                                     choices = "",
                                                     options= list(
                                                       create =TRUE
                                                     )),
                                      textInput("tccStepNrText", "Step Number",
                                                ""),
                                      textInput("tccStepDescriptionText", 
                                                "Description",
                                                ""),
                                      wellPanel(
                                        selectInput("tccStepTypeSlct",
                                                    "Step Type",
                                                    choices = c("temperature",
                                                                "gradient",
                                                                "loop",
                                                                "pause",
                                                                "lidOpen")),
                                        conditionalPanel(
                                          "input.tccStepTypeSlct == 'gradient'",
                                          textInput("tccStepHighTemperatureText", 
                                                    "High Temperature",
                                                    ""),
                                          textInput("tccStepLowTemperatureText", 
                                                    "Low Temperature",
                                                    "")),
                                        conditionalPanel(
                                          "input.tccStepTypeSlct == 'temperature' || input.tccStepTypeSlct == 'pause'",
                                          textInput("tccStepTemperatureText", 
                                                    "Temperature",
                                                    "")),
                                        conditionalPanel(
                                          "input.tccStepTypeSlct == 'temperature' || input.tccStepTypeSlct == 'gradient'",
                                          textInput("tccStepDurationText", 
                                                    "Duration",
                                                    ""),
                                          textInput("tccStepTemperatureChangeText", 
                                                    "Temperature Change",
                                                    ""),
                                          textInput("tccStepDurationChangeText", 
                                                    "Duration Change",
                                                    ""),
                                          selectInput("tccStepMeasureText", 
                                                      "Measure",
                                                      choices = c("real time",
                                                                  "meltcurve")),
                                          textInput("tccStepRampText", 
                                                    "Ramp",
                                                    "")),
                                        conditionalPanel(
                                          "input.tccStepTypeSlct == 'loop'",
                                          textInput("tccStepGotoText", 
                                                    "Go To",
                                                    ""),
                                          textInput("tccStepRepeatText", 
                                                    "Repeat",
                                                    "")),
                                        conditionalPanel(
                                          "input.tccStepTypeSlct == 'lidOpen'",
                                          checkboxInput("tccStepLidOpenChk", 
                                                        "Lid Open",
                                                        FALSE)
                                        ),
                                        actionButton("removeTccStepBtn",
                                                     "Remove Step")
                                      )),
                            actionButton("removeTccBtn",
                                         "Remove Thermal Cycling Conditions")),
                   tabPanel("Experiment", 
                            selectizeInput("experimentSlct",
                                           "Select Experiment",
                                           choices = "",
                                           options= list(
                                             create =TRUE
                                           )),
                            textInput("experimentIdText", "ID",
                                      ""),
                            textInput("experimentDescriptionText", 
                                      "Description",
                                      ""),
                            selectInput("experimentDocumentationSlct",
                                        "Documentation",
                                        multiple = TRUE,
                                        choices = ""),
                            wellPanel(
                              "Run",
                              selectizeInput("runSlct",
                                             "Select Run",
                                             choices = "",
                                             options= list(
                                               create =TRUE
                                             )),
                              textInput("runIdText", "ID",
                                        ""),
                              textInput("runDescriptionText", 
                                        "Description",
                                        ""),
                              selectInput("runDocumentationSlct",
                                          "Documentation",
                                          multiple = TRUE,
                                          choices = ""),
                              selectInput("runExperimenterSlct",
                                          "Experimenter",
                                          multiple = TRUE,
                                          choices = ""),
                              textInput("runInstrumentText", "Instrument",
                                        ""),
                              wellPanel("Data Collection Software",
                                        textInput("runDataCollectionSoftwareNameText",
                                                  "Name",
                                                  ""),
                                        textInput("runDataCollectionSoftwareVersionText",
                                                  "Version",
                                                  "")),
                              textInput("runBackgroundDeterminationMethodText",
                                        "Background Determination Method",
                                        ""),
                              selectInput("runCqDetectionMethodSlct",
                                          "Cq Detection Method",
                                          choices = c("",
                                                      "automated threshold and baseline settings",
                                                      "manual threshold and baseline settings",
                                                      "second derivative maximum",
                                                      "other")),
                              selectInput("runTccSlct",
                                          "Thermal Cycling Conditions",
                                          choices = ""),
                              wellPanel(
                                "PCR fromat",
                                textInput("runRowsText", "Rows",
                                          ""),
                                textInput("runColumnsText", "Columns",
                                          ""),
                                selectInput("runRowLabelSlct",
                                            "Row Label",
                                            choices = c("ABC",
                                                        "123",
                                                        "A1a1")),
                                selectInput("runColumnLabelSlct",
                                            "Column Label",
                                            choices = c("123",
                                                        "ABC",
                                                        "A1a1"))
                                
                              ),
                              textInput("runDateText", "Run Date",
                                        ""),
                              wellPanel(
                                "React",
                                selectizeInput("reactSlct",
                                               "Select React",
                                               choices = "",
                                               options= list(
                                                 create =TRUE
                                               )),
                                textInput("reactIdText", "ID",
                                          ""),
                                selectInput("reactSampleSlct",
                                            "Sample",
                                            choices = ""),
                                wellPanel(
                                  "Data",
                                  selectizeInput("dataSlct",
                                                 "Select Data",
                                                 choices = "",
                                                 options= list(
                                                   create =TRUE
                                                 )),
                                  selectInput("dataTarSlct",
                                              "Target",
                                              choices = ""),
                                  textInput("dataCqText", "Cq",
                                            ""),
                                  textInput("dataExclText", "Excluded",
                                            ""),
                                  textInput("dataEndPtText", "End Point",
                                            ""),
                                  textInput("dataBgFluorText", 
                                            "Background Fluorescence",
                                            ""),
                                  textInput("dataBgFluorSlpText", 
                                            "Background Fluorescence Slope",
                                            ""),
                                  textInput("dataQuantFluorText", 
                                            "Quantification Fluorescence",
                                            ""),
                                  actionButton("removeDataBtn",
                                               "Remove Data")
                                ),
                                actionButton("removeReactBtn",
                                             "Remove React")
                              ),
                              actionButton("removeRunBtn",
                                           "Remove Run")
                            ),
                            actionButton("removeExperimentBtn",
                                         "Remove Experiment")
                   )
                   
        ),
        tabPanel("qPCR",
                 fluidRow(
                   # column(2,
                   #        numericInput("removeFirstRows",
                   #                     "Remove First N Rows",
                   #                     0, 0, step = 1)),
                   column(4,
                          checkboxInput("preprocessqPCR",
                                        "Preprocess")),
                   column(4,
                          selectInput("smoothqPCRmethod",
                                      "Smoothing method",
                                      c("None" = "none",
                                        "LOWESS" = "lowess",
                                        "Moving average" = "mova",
                                        "Savitzky-Golay (recommended)" = "savgol",
                                        "Cubic spline smooth (recommended)" = "smooth",
                                        "Standard cubic spline smooth" = "spline",
                                        "Friedman's SuperSmoother" = "supsmu",
                                        "Whittaker 1" = "whit1",
                                        "Whittaker 2" = "whit2"
                                        # ,"All" = "all"
                                      ))),
                   column(4,
                          selectInput("normqPCRmethod",
                                      "Normalization method",
                                      c("None" = "none",
                                        "Min-max" = "minm",
                                        "Maximum normalization" = "max",
                                        "Quantile normalization" = "luqn",
                                        "z-score" = "zscore")))),
                 fluidRow(
                   column(4,
                          selectInput("cqMethod",
                                      "Cq method",
                                      c("None" = "none",
                                        "Threshold" = "th",
                                        "SDM" = "sdm"))),
                   conditionalPanel(
                     condition = "input.cqMethod == 'th'",
                     column(4,
                            checkboxInput("autoThLevel",
                                          "Auto Threshold",
                                          TRUE)),
                     conditionalPanel(
                       condition = "input.autoThLevel == false",
                       column(4,
                              uiOutput("thLevelsUI"))))
                   # column(2,
                   #        actionButton("recalculateCq",
                   #                     "Recalculate Cq"))
                 ),
                 wellPanel(
                   fluidRow(
                     column(2,
                            selectInput("colorqPCRby",
                                        "Color by",
                                        c("None" = "none",
                                          "Experiment" = "exp.id",
                                          "Run" = "run.id",
                                          "Target" = "target",
                                          "Dye" = "target.dyeId",
                                          "Sample" = "sample",
                                          "Sample Type" = "sample.type",
                                          "Position" = "position"))),
                     column(2,
                            selectInput("shapeqPCRby",
                                        "Line Type by",
                                        c("None" = "none",
                                          "Experiment" = "exp.id",
                                          "Run" = "run.id",
                                          "Target" = "target",
                                          "Dye" = "target.dyeId",
                                          "Sample" = "sample",
                                          "Sample Type" = "sample.type",
                                          "Position" = "position"))),
                     column(2,
                            selectInput("showTargetsadp",
                                        "Show Targets",
                                        multiple = TRUE,
                                        choices = "")),
                     column(2,
                            selectInput("showCq",
                                        "Show Cq",
                                        c("None" = "none",
                                          "Yes" = "yes",
                                          "Mean for replicates" = "mean"))),
                     column(2,
                            checkboxInput("logScale",
                                          "Log Scale"))),
                   fluidRow(
                     column(6, plotlyOutput("qPCRPlot")),
                     column(6, wellPanel(
                            fluidRow(column(4, selectInput("showqPCRExperiment",
                                                        "Experiment", c())),
                                     column(4, selectInput("showqPCRRun",
                                                        "Run", c()))),
                            htmlOutput("plateTbl"))))),
                 dataTableOutput("qPCRDt"),
                 value = "adp"),
        tabPanel("Melting Curves",
                 
                   fluidRow(
                     column(2,
                            checkboxInput("preprocessMelting",
                                          "Preprocess")),
                     conditionalPanel(
                       condition = "input.preprocessMelting == true",
                       column(2,
                              checkboxInput("bgAdjMelting",
                                            "Adjust the Background Signal",
                                            FALSE)),
                       conditionalPanel(
                         condition = "input.bgAdjMelting == true",
                         column(2,
                                sliderInput("bgRangeMelting", 
                                            label = "Temperature Background Range (°C)", min = 0, 
                                            max = 100, value = c(50, 55), step = 1))),
                       column(2,
                              checkboxInput("minMaxMelting",
                                            "Min-Max Normalization",
                                            FALSE)),
                       column(2,
                              sliderInput("dfFactMelting", 
                                          label = "Factor to Smooth the Curve", min = 0.6, 
                                          max = 1.1, value = 0.95, step = 0.05))
                     )
                   ),
                 wellPanel(
                   fluidRow(
                     column(2,
                            selectInput("colorMeltingBy",
                                        "Color by",
                                        c("None" = "none",
                                          "Experiment" = "exp.id",
                                          "Run" = "run.id",
                                          "Target" = "target",
                                          "Dye" = "target.dyeId",
                                          "Sample" = "sample",
                                          "Sample Type" = "sample.type",
                                          "Position" = "position"))),
                     column(2,
                            selectInput("shapeMeltingBy",
                                        "Line Type by",
                                        c("None" = "none",
                                          "Experiment" = "exp.id",
                                          "Run" = "run.id",
                                          "Target" = "target",
                                          "Dye" = "target.dyeId",
                                          "Sample" = "sample",
                                          "Sample Type" = "sample.type",
                                          "Position" = "position"))),
                     column(2,
                            selectInput("showTargetsmdp",
                                        "Show Targets",
                                        multiple = TRUE,
                                        choices = ""))
                     ),
                   fluidRow(
                     column(6,
                     wellPanel(
                       fluidRow(column(4, selectInput("showMeltingExperiment",
                                                      "Experiment", c())),
                                column(4, selectInput("showMeltingRun",
                                                      "Run", c()))),
                       htmlOutput("plateTblMelting")))),
                   plotlyOutput("meltingPlot")),
                 dataTableOutput("meltingDt"),
                 value = "mdp"),
        tabPanel("Store",
                 wellPanel(downloadButton("downloadRDML",
                                          "Store RDML"),
                           tags$p("Note that if you made any preprocession all fluorescence points will be overwritten with the new calculated values!!!"))),
        tabPanel("Help",
                 includeMarkdown("md/help.md")),
        id = "mainNavbar"
      ),
      wellPanel(
        h4("Log:"),
        actionButton("clearLogBtn",
                     "Clear"),
        uiOutput("logText")
      )
    )
  )
)
