source("funcs/functions.R", local = TRUE)
# load modules
for (f in list.files('./modules')) {
  source(file.path('modules', f), local=TRUE)
}

# Define UI for application
shinyUI(tagList(
  shinyjs::useShinyjs(),
  navbarPage(theme=shinythemes::shinytheme('united'), id='tabs', collapsible=TRUE,
             title='Wallace',
             tabPanel("Intro", value=0),
             tabPanel("1 Occ Data", value=1),
             tabPanel("2 Process Occs", value=2),
             tabPanel("3 Env Data", value=3),
             tabPanel("4 Process Envs", value=4),
             tabPanel("5 Partition Occs", value=5),
             tabPanel("6 Model", value=6),
             tabPanel("7 Visualize", value=7),
             tabPanel("8 Project", value=8),
             tabPanel("Session Code", value='rmd'),
             
             fluidRow(column(4,
                             wellPanel(
                               includeCSS("css/styles.css"),
                               includeScript("js/scroll.js"),
                               conditionalPanel("input.tabs == 0",
                                                #actionButton('load', 'HACK'),
                                                includeMarkdown("Rmd/text_intro_tab.Rmd")
                               ),
                               # COMPONENT 1 ####
                               conditionalPanel("input.tabs == 1",
                                                h4("Obtain Occurrence Data"),
                                                radioButtons("occSel", "Modules Available:",
                                                             choices = list("Query Database" = 'db', "User-specified" = 'user'),
                                                             selected = 'db'),
                                                HTML('<hr>'),
                                                conditionalPanel("input.occSel == 'db'",
                                                                 div('Module: Query Database', id="mod"),
                                                                 uiTop('spocc', 'Interface to Species Occurrence Data Sources'),
                                                                 HTML('<hr>'),
                                                                 queryDb_UI('c1_queryDb'),
                                                                 actionButton("goDbOccs", "Query Database"), br(), br(),
                                                                 HTML('<hr>'),
                                                                 strong("Download database occurrence localities (.csv)"), br(), br(),
                                                                 downloadButton('dlDbOccs', "Download"),
                                                                 HTML('<hr>'),
                                                                 uiBottom("Jamie M. Kass, Bruno Vilela, Robert P. Anderson", 'spocc', "Scott Chamberlain, Karthik Ram, Ted Hart")
                                                ),
                                                conditionalPanel("input.occSel == 'user'",
                                                                 div('Module: User-specified Occurrences', id="mod"),
                                                                 HTML('<hr>'),
                                                                 userOccs_UI('c1_userOccs'),
                                                                 actionButton("goUserOccs", "Load Occurrences"),
                                                                 HTML('<hr>'),
                                                                 div('Module Developers: Jamie M. Kass, Bruno Vilela, Robert P. Anderson', id="pkgDes")
                                                )
                               ),
                               # COMPONENT 2 ####
                               conditionalPanel("input.tabs == 2",
                                                h4("Process Occurrence Data"),
                                                radioButtons("procOccSel", "Modules Available:",
                                                             choices = list("Select Occurrences On Map" = 'selOccs',
                                                                            "Remove Occurrences By ID" = 'remID',
                                                                            "Spatial Thin" = 'spthin')),
                                                HTML('<hr>'),
                                                conditionalPanel("input.procOccSel == 'selOccs'",
                                                                 div('Module: Select Occurrences On Map', id="mod"),
                                                                 uiTop('leaflet.extras', "Extra functionality for 'leaflet' Package"),
                                                                 HTML('<hr>'),
                                                                 selectOccs_UI('c2_selectOccs'),
                                                                 strong("Select occurrences intersecting drawn polygon"), br(),
                                                                 "(", HTML("<font color='blue'><b>NOTE</b></font>"), 
                                                                 ': to begin drawing, click hexagon icon on map toolbar, 
                                                                 and when complete, press "Finish" and then the "Select Occurrences" button)', br(), br(),
                                                                 actionButton("goSelectOccs", "Select Occurrences")
                                                ),
                                                conditionalPanel("input.procOccSel == 'remID'",
                                                                 div('Module: Remove Occurrences By ID', id="mod"),
                                                                 HTML('<hr>'),
                                                                 removeByID_UI('c2_removeByID'),
                                                                 actionButton("goRemoveByID", "Remove Occurrence")
                                                ),
                                                # placeholder for select on map
                                                conditionalPanel("input.procOccSel == 'spthin'",
                                                                 div('Module: Spatial Thin', id="mod"),
                                                                 uiTop('spThin', 'Spatial Thinning of Species Occurrence Records'),
                                                                 HTML('<hr>'),
                                                                 thinOccs_UI('c2_thinOccs'),
                                                                 actionButton("goThinOccs", "Thin Occurrences")
                                                ), br(),
                                                strong("Reset to original occurrences"), br(), br(),
                                                actionButton("goResetOccs", "Reset"),
                                                HTML('<hr>'),
                                                strong("Download processed occurrence localities (.csv)"), br(), br(),
                                                downloadButton('dlProcOccs', "Download"),
                                                HTML('<hr>'),
                                                conditionalPanel("input.procOccSel == 'selOccs'",
                                                                 uiBottom("Jamie M. Kass, Robert P. Anderson", 'leaflet.extras', 'Bhaskar Karambelkar, Bangyou Zheng')),
                                                conditionalPanel("input.procOccSel == 'remID'",
                                                                 uiBottom("Jamie M. Kass, Robert P. Anderson")),
                                                conditionalPanel("input.procOccSel == 'spthin'",
                                                                 uiBottom("Jamie M. Kass, Matthew E. Aiello-Lammens, Robert P. Anderson", 'spThin', "Matthew E. Aiello-Lammens, Rob A. Boria, 
                                                                                          Alex Radosavljevic, Bruno Vilela, Robert P. Anderson"),
                                                                 " | ", a("software note", href="http://onlinelibrary.wiley.com/doi/10.1111/ecog.01132/abstract", target = "_blank"))
                               ),
                               # COMPONENT 3 ####
                               conditionalPanel("input.tabs == 3",
                                                h4("Obtain Environmental Data"),
                                                radioButtons("envDataSel", "Modules Available:",
                                                             choices = list("WorldClim Bioclims" = 'wcbc',
                                                                            "User-specified" = 'user')),
                                                HTML('<hr>'),
                                                conditionalPanel("input.envDataSel == 'wcbc'",
                                                                 div('Module: WorldClim Bioclims', id="mod"),
                                                                 uiTop('raster', 'Geographic Data Analysis and Modeling'),
                                                                 HTML('<hr>'),
                                                                 wcBioclims_UI("c3_wcBioclims"),
                                                                 strong("Using map center coordinates as reference for tile download."),
                                                                 textOutput('ctrLatLon'), br(),
                                                                 actionButton("goEnvData", "Load Env Data")
                                                ),
                                                conditionalPanel("input.envDataSel == 'user'",
                                                                 div('Module: User-specified Environmental Data', id="mod"),
                                                                 HTML('<hr>'),
                                                                 userEnvs_UI('c3_userEnvs'),
                                                                 actionButton('goUserEnvs', 'Load Env Data')
                                                ),
                                                # br(), br(),
                                                # strong("Download environmental predictors"), br(), br(),
                                                # downloadButton('dlEnvs', "Download"),
                                                HTML('<hr>'),
                                                uiBottom("Jamie M. Kass, Gonzalo E. Pinilla-Buitrago, Robert P. Anderson", 'raster', "Robert J. Hijmans, Jacob van Etten, Joe Cheng, Matteo Mattiuzzu, 
                                                         Michael Sumner, Jonathan A. Greenberg, Oscar Perpinan Lamigueriro, Andrew Bevan, 
                                                         Etienne B. Racine, Ashton Shortridge"),
                                                " | ", a("WorldClim", href="http://worldclim.org", target="_blank")
                                                
                               ),
                               # COMPONENT 4 ####
                               conditionalPanel("input.tabs == 4",
                                                h4("Process Environmental Data"),
                                                radioButtons("envProcSel", "Modules Available:",
                                                             choices = list("Select Study Region" = "bgSel",
                                                                            "User-specified" = "bgUser")),
                                                
                                                HTML('<hr>'),
                                                conditionalPanel("input.envProcSel == 'bgSel'",
                                                                 div('Module: Select Study Region', id="mod"),
                                                                 uiTop('sp', 'Title Classes and Methods for Spatial Data'),
                                                                 uiTop('rgeos', 'Interface to Geometry Engine - Open Source (GEOS)'),
                                                                 HTML('<hr>'),
                                                                 div("Step 1:", id="step"), div("Choose Background Extent", id="stepText"), br(), br(),
                                                                 bgExtent_UI('c4_bgExtent'),
                                                                 actionButton("goBgExt", "Select")),
                                                conditionalPanel("input.envProcSel == 'bgUser'",
                                                                 div('Module: User-specified Study Region', id="mod"),
                                                                 div("Step 1:", id="step"), div("Choose Background Extent", id="stepText"), br(), br(),
                                                                 userBgExtent_UI('c4_userBgExtent'),
                                                                 actionButton("goUserBg", "Load")),
                                                conditionalPanel("input.envProcSel == 'bgSel' | input.envProcSel == 'bgUser'",
                                                                 HTML('<hr>'),
                                                                 div("Step 2:", id="step"), div("Sample Background Points", id="stepText"), br(), br(),
                                                                 strong('Mask predictor rasters by background extent and sample background points'), br(), br(),
                                                                 bgMskAndSamplePts_UI('c4_bgMskAndSamplePts'),
                                                                 actionButton("goBgMask", "Sample"), br(), br(),
                                                                 HTML('<hr>'),
                                                                 selectInput('bgMskFileType', label = "Select download file type",
                                                                             choices = list("GRD" = 'raster', "ASCII" = 'ascii', "GeoTIFF" = 'GTiff')),
                                                                 strong("Download predictor rasters masked to background extent"), br(), br(),
                                                                 downloadButton('dlMskEnvs', "Download"),
                                                                 HTML('<hr>'),
                                                                 uiBottom("Jamie M. Kass, Bruno Vilela, Robert P. Anderson", 'sp', "Edzer Pebesma, Roger Bivand, Barry Rowlingson, Virgilio Gomez-Rubio,
                                                                          Robert Hijmans, Michael Sumner, Don MacQueen, Jim Lemon, Josh O\'Brien"), br(),
                                                                 uiBottom(NULL, 'rgeos', "Roger Bivand, Colin Rundel, Edzer Pebesma, Karl Ove Hufthammer"))
                                                
                               ),
                               # COMPONENT 5 ####
                               conditionalPanel("input.tabs == 5",
                                                h4("Partition Occurrence Data"),
                                                radioButtons("partSel", "Modules Available:",
                                                             choices = list("Non-spatial Partition" = 'nsp',
                                                                            "Spatial Partition" = 'sp')),
                                                HTML('<hr>'),
                                                conditionalPanel("input.partSel == 'sp'",
                                                                 div('Module: Spatial Partition', id="mod"),
                                                                 uiTop('ENMeval', 'Automated Runs and Evaluations of Ecological Niche Models'),
                                                                 HTML('<hr>'),
                                                                 partSp_UI('c5_partSp'),
                                                                 actionButton("goPartSp", "Partition")),
                                                conditionalPanel("input.partSel == 'nsp'",
                                                                 div('Module: Non-spatial Partition', id="mod"),
                                                                 uiTop('ENMeval', 'Automated Runs and Evaluations of Ecological Niche Models'),
                                                                 HTML('<hr>'),
                                                                 partNsp_UI('c5_partNsp'),
                                                                 actionButton("goPartNsp", "Partition")),
                                                HTML('<hr>'),
                                                strong("Download occurrence and background localities with partition values (.csv)"), br(), br(),
                                                downloadButton('dlPart', "Download"),
                                                HTML('<hr>'),
                                                uiBottom("Jamie M. Kass, Bruno Vilela, Robert P. Anderson", 'ENMeval', 'Robert Muscarella, Peter J. Galante, Mariano Soley-Guardia, Robert A. Boria,
                                                                           Jamie M. Kass, Maria Uriarte, Robert P. Anderson'),
                                                " | ", a("software note", href="http://onlinelibrary.wiley.com/doi/10.1111/2041-210X.12261/abstract", target = "_blank")
                               ),
                               # COMPONENT 6 ####
                               conditionalPanel("input.tabs == 6",
                                                h4("Build and Evaluate Niche Model"),
                                                radioButtons("enmSel", "Modules Available:",
                                                             choices = list("BIOCLIM", "Maxent")),
                                                HTML('<hr>'),
                                                conditionalPanel("input.enmSel == 'Maxent'",
                                                                 div('Module: Maxent', id="mod"),
                                                                 uiTop('ENMeval', 'Automated Runs and Evaluations of Ecological Niche Models using Maxent GUI (Java)'),
                                                                 uiTop('dismo', 'Species Distribution Modeling'),
                                                                 uiTop('maxnet', "Fitting 'Maxent' Species Distribution Models with 'glmnet'"),
                                                                 HTML('<hr>'),
                                                                 htmlOutput('maxentJar'), br(),
                                                                 "(", HTML("<font color='blue'><b>NOTE</b></font>"), 
                                                                 ": see module guidance for troubleshooting tips if you are experiencing problems.)",
                                                                 HTML('<hr>'),
                                                                 maxent_UI('c6_maxent'),
                                                                 actionButton('goMaxent', 'Run')),
                                                conditionalPanel("input.enmSel == 'BIOCLIM'",
                                                                 div('Module: BIOCLIM', id="mod"),
                                                                 uiTop('ENMeval', 'Automated Runs and Evaluations of Ecological Niche Models'),
                                                                 uiTop('dismo', 'Species Distribution Modeling'),
                                                                 HTML('<hr>'),
                                                                 bioclim_UI('c6_bioclim'),
                                                                 actionButton('goBioclim', 'Run')),
                                                HTML('<hr>'),
                                                downloadButton('dlEvalTbl', "Download CSV"),
                                                HTML('<hr>'),
                                                uiBottom("Jamie M. Kass, Gonzalo E. Pinilla-Buitrago, Robert Muscarella, Bruno Vilela, Robert P. Anderson", 'ENMeval', 'Robert Muscarella, Peter J. Galante, Mariano Soley-Guardia, Robert A. Boria,
                                                         Jamie M. Kass, Maria Uriarte, Robert P. Anderson'),
                                                " | ", a("software note", href="http://onlinelibrary.wiley.com/doi/10.1111/2041-210X.12261/abstract", target = "_blank"), br(),
                                                uiBottom(NULL, 'dismo', 'Robert J. Hijmans, Steven Phillips, John Leathwick, Jane Elith'), br(),
                                                uiBottom(NULL, 'maxnet', 'Steven Phillips')
                               ),
                               # COMPONENT 7 ####
                               conditionalPanel("input.tabs == 7", 
                                                h4("Visualize Model Results"),
                                                radioButtons("visSel", "Modules Available:",
                                                             choices = list("BIOCLIM Envelope Plots" = 'bcPlots',
                                                                            "Maxent Evaluation Plots" = 'mxEval',
                                                                            "Plot Response Curves" = 'response',
                                                                            "Map Prediction" = 'map')),
                                                HTML('<hr>'),
                                                conditionalPanel("input.visSel == 'bcPlots'",
                                                                 div('Module: BIOCLIM Envelope Plots', id="mod"),
                                                                 uiTop('dismo', 'Species Distribution Modeling'),
                                                                 HTML('<hr>'),
                                                                 bcPlots_UI('c7_bcPlots')),
                                                conditionalPanel("input.visSel == 'mxEval'",
                                                                 div('Module: Maxent Evaluation Plots', id="mod"),
                                                                 uiTop('ENMeval', 'Automated Runs and Evaluations of Ecological Niche Models'),
                                                                 uiTop('dismo', 'Species Distribution Modeling'),
                                                                 HTML('<hr>'),
                                                                 mxEvalPlots_UI('c7_mxEvalPlots')),
                                                conditionalPanel("input.visSel == 'response'",
                                                                 div('Module: Response Curves', id="mod"),
                                                                 uiTop('dismo', 'Species Distribution Modeling'),
                                                                 HTML('<hr>'),
                                                                 respPlots_UI('c7_respPlots')),
                                                conditionalPanel("input.visSel == 'map'",
                                                                 div('Module: Map Prediction', id="mod"),
                                                                 uiTop('dismo', 'Species Distribution Modeling'),
                                                                 HTML('<hr>'),
                                                                 conditionalPanel("input.enmSel == 'Maxent'", mapPredsMaxent_UI('c7_mapPredsMaxent')), 
                                                                 conditionalPanel("input.enmSel != 'Maxent'", mapPreds_UI('c7_mapPreds')),
                                                                 actionButton("goMapPreds", "Plot"), br(), br(),
                                                                 HTML('<hr>'),
                                                                 selectInput('predFileType', label = "Select download file type",
                                                                             choices = list("GRD" = 'raster', "ASCII" = 'ascii', 
                                                                                            "GeoTIFF" = 'GTiff', "PNG" = "png")),
                                                                 strong("Download displayed raster"), br(), br(),
                                                                 downloadButton('dlPred', "Download")),
                                                HTML('<hr>'),
                                                conditionalPanel("input.visSel == 'mxEval'",
                                                                 uiBottom("Jamie M. Kass, Robert Muscarella, Bruno Vilela, Robert P. Anderson", 'ENMeval', 'Robert Muscarella, Peter J. Galante, Mariano Soley-Guardia, Robert A. Boria,
                                                         Jamie M. Kass, Maria Uriarte, Robert P. Anderson'),
                                                                 " | ", a("software note", href="http://onlinelibrary.wiley.com/doi/10.1111/2041-210X.12261/abstract", target = "_blank"), br()
                                                ),
                                                conditionalPanel("input.visSel != 'mxEval'",
                                                                 uiBottom("Jamie M. Kass, Gonzalo E. Pinilla-Buitrago, Bruno Vilela, Robert P. Anderson")
                                                ),
                                                uiBottom(NULL, 'dismo', 'Robert J. Hijmans, Steven Phillips, John Leathwick, Jane Elith')
                               ),
                               # COMPONENT 8 ####
                               conditionalPanel("input.tabs == 8",
                                                h4("Project Model"),
                                                radioButtons("projSel", "Modules Available:",
                                                             choices = list("Project to New Extent" = 'projArea',
                                                                            "Project to New Time" = 'projTime',
                                                                            "Calculate Environmental Similarity" = 'mess'),
                                                             selected = 'projArea'),
                                                HTML('<hr>'),
                                                conditionalPanel("input.projSel == 'projArea'",
                                                                 div('Module: Project to New Extent', id="mod"),
                                                                 uiTop('dismo', 'Species Distribution Modeling'),
                                                                 HTML('<hr>'),
                                                                 strong("Project model to current extent"), br(), br(),
                                                                 actionButton('goProjectArea', "Project"), br(), br(),
                                                                 projectArea_UI('c8_projectArea')),
                                                conditionalPanel("input.projSel == 'projTime'",
                                                                 div('Module: Project to New Time', id="mod"),
                                                                 uiTop('dismo', 'Species Distribution Modeling'),
                                                                 HTML('<hr>'),
                                                                 projectTime_UI('c8_projectTime'),
                                                                 strong("Project model to new time for current extent"), br(), br(),
                                                                 actionButton('goProjectTime', "Project")),
                                                conditionalPanel("input.projSel == 'mess'",
                                                                 div('Module: Calculate Environmental Similarity', id="mod"),
                                                                 uiTop('dismo', 'Species Distribution Modeling'),
                                                                 HTML('<hr>'),
                                                                 envSimilarity_UI('c8_envSimilarity'),
                                                                 strong("Calculate MESS for current extent"), br(), br(),
                                                                 actionButton('goEnvSimilarity', "Calculate MESS")),
                                                strong("Reset projection extent"), br(), br(),
                                                actionButton("goResetProj", "Reset"),
                                                HTML('<hr>'),
                                                selectInput('projFileType', label = "Select download file type",
                                                            choices = list("GRD" = 'raster', "ASCII" = 'ascii', "GeoTIFF" = 'GTiff',
                                                                           "PNG" = "png")),
                                                strong("Download displayed raster"), br(), br(),
                                                downloadButton('dlProj', "Download"),
                                                HTML('<hr>'),
                                                uiBottom("Jamie M. Kass, Gonzalo E. Pinilla-Buitrago, Bruno Vilela, Robert P. Anderson", 'dismo', 'Robert J. Hijmans, Steven Phillips, John Leathwick, Jane Elith')
                               ),
                               # SESSION CODE ####
                               conditionalPanel("input.tabs == 'rmd'",
                                                h4("Download Session Code"),
                                                HTML('<hr>'),
                                                uiTop('rmarkdown', 'Dynamic Documents for R'),
                                                uiTop('knitr', 'A General-Purpose Package for Dynamic Report Generation in R'),
                                                HTML('<hr>'),
                                                selectInput('rmdFileType', label = "Select download file type",
                                                            choices = list("Rmd", "PDF", "HTML", "Word")),
                                                downloadButton('dlRMD', 'Download Session Code'),
                                                HTML('<hr>'),
                                                uiBottom("Jamie M. Kass, Gonzalo E. Pinilla-Buitrago, Bruno Vilela, Robert P. Anderson", 'rmarkdown', 'JJ Allaire, Joe Cheng, Yihui Xie, Jonathan McPherson, 
                                                       Winston Chang, Jeff Allen, Hadley Wickham, Aron Atkins, Rob Hyndman, Ruben Arslan'), br(),
                                                uiBottom(NULL, 'knitr', 'Yihui Xie')
                               )
                             )),
                      # RESULTS WINDOW ####
                      column(8,
                             conditionalPanel("input.tabs != 0 & input.tabs != 'rmd'",
                                              div(id = "wallaceLog", class = "scrollbox", htmlOutput("log")),
                                              absolutePanel(top = -10, right = 20, width = 150, draggable = TRUE,
                                                            selectInput("bmap", "Change Base Map", 
                                                                        choices = c('ESRI Topo'="Esri.WorldTopoMap",
                                                                                    'Stamen Terrain'="Stamen.Terrain",
                                                                                    'Open Topo'="OpenTopoMap",
                                                                                    'ESRI Imagery'="Esri.WorldImagery",
                                                                                    'ESRI Nat Geo'='Esri.NatGeoWorldMap'),
                                                                        selected = "Esri.WorldTopoMap")),
                                              absolutePanel(top = 60, right = 20, width = 150, draggable = TRUE,
                                                            uiOutput("modSelUI")),
                                              absolutePanel(top = 60, right = 180, width = 150, draggable = TRUE,
                                                            uiOutput("envSelUI"))
                             ),
                             br(),
                             conditionalPanel("input.tabs != 'rmd' & input.tabs != 0",
                                              tabsetPanel(id = 'main',
                                                          tabPanel('Map', leaflet::leafletOutput("map", height=600)),
                                                          tabPanel('Occs Tbl', br(), br(), DT::dataTableOutput('occTbl')),
                                                          tabPanel('Results', 
                                                                   conditionalPanel("input.tabs == 3", verbatimTextOutput('envsPrint')),
                                                                   conditionalPanel("input.tabs == 6", uiOutput('evalTbls')),
                                                                   conditionalPanel("input.tabs == 7 && input.visSel == 'response'",
                                                                                    imageOutput('respPlots')),
                                                                   conditionalPanel("input.tabs == 7 && input.visSel == 'bcPlots' && input.enmSel == 'BIOCLIM'",
                                                                                    imageOutput('bcEnvelPlot')),
                                                                   conditionalPanel("input.tabs == 7 && input.visSel == 'mxEval'  && input.enmSel == 'Maxent'",
                                                                                    imageOutput('mxEvalPlots'))
                                                          ),
                                                          tabPanel('Component Guidance', uiOutput('gtext_comp')),
                                                          tabPanel('Module Guidance', uiOutput('gtext_mod'))
                                              )
                             ),
                             conditionalPanel("input.tabs == 'rmd'",
                                              column(8,
                                                     includeMarkdown("Rmd/text_sessionCode.Rmd")
                                              )
                             ),
                             conditionalPanel("input.tabs == 0",
                                              tabsetPanel(id = 'introTabs',
                                                          tabPanel('Intro', includeMarkdown("Rmd/text_intro.Rmd")),
                                                          tabPanel('About',
                                                                   fluidRow(
                                                                     column(8, includeMarkdown("Rmd/text_about.Rmd")
                                                                     )
                                                                   )
                                                          )
                                              )
                             )
                      )
             )
  )
))
