make_tbl_location <- function(x) {
  console_log("make_nppsd.r", "make_tbl_location() start")
  # Required fields
  if (!("Weather" %in% colnames(x$all_points_data))) {
    x$all_points_data$Weather <- as.character(NA)
  }
  if (!("Beaufort" %in% colnames(x$all_points_data))) {
    x$all_points_data$Beaufort <- as.integer(NA)
  }
  suppressWarnings(
    odata <- x$all_points_data %>%
      transmute(
        master_key = glue(
          "{TripID}_",
          "{str_pad(Transect, 4, pad = '0')}_",
          "{year(timestamp)}",
          "{sprintf('%02d', month(timestamp))}",
          "{sprintf('%02d', day(timestamp))}_",
          "{sprintf('%02d', nppsd_split_id)}"
        ),
        beaufort = Beaufort,
        weather = Weather
      ) %>%
      group_by(master_key) %>%
      summarize(
        beaufort = max(
          Modes(as.numeric(beaufort)),
          na.rm = TRUE
        ),
        weather = max(
          Modes(weather),
          na.rm = TRUE
        ),
        .groups = "drop"
      )
  )

  x$tbl_location <- x$transects %>%
    mutate(Date = date(start_time)) %>%
    inner_join(x$nppsd_split, by = c("TripID", "Transect", "Date")) %>%
    inner_join(x$nppsd_track_centroids,
      by = c("TripID", "Transect", "Date", "nppsd_split_id")
    ) %>%
    mutate(master_key = glue(
      "{TripID}_",
      "{str_pad(Transect, 4, pad = '0')}_",
      "{year(start_time.y)}",
      "{sprintf('%02d', month(start_time.y))}",
      "{sprintf('%02d', day(start_time.y))}_",
      "{sprintf('%02d', nppsd_split_id)}"
    )) %>%
    # This preserves transects without obs,
    # but beaufort/weather will be NA
    left_join(odata, by = "master_key") %>%
    transmute(
      master_key = master_key,
      modified_platform_type = if_else(
        str_length(input$modified_platform_type) > 0,
        input$modified_platform_type, as.character(NA)
      ),
      modified_survey_type = if_else(
        str_length(input$modified_survey_type) > 0,
        input$modified_survey_type, as.character(NA)
      ),
      location_local_date_time = format(
        start_time.y,
        "%Y-%m-%d %H:%M:%S"
      ),
      location_utc_date_time = format(
        with_tz(start_time.y, tzone = "UTC"),
        "%Y-%m-%d %H:%M:%S"
      ),
      survey_target = case_when(
        str_length(input$survey_target) > 0 &
          input$survey_target == "Other" &
          str_length(input$survey_target_other) > 0 ~ input$survey_target_other,
        str_length(input$survey_target) > 0 ~ input$survey_target,
        TRUE ~ NA_character_
      ),
      fly_bird_method = if_else(
        str_length(input$fly_bird_method) > 0,
        input$fly_bird_method, as.character(NA)
      ),
      loc_method = "Centroid",
      latitude = Latitude,
      longitude = Longitude,
      transect_width = as.numeric(gsub("([0-9.]+).*", "\\1", TxWidth)),
      sea_state = beaufort,
      weather = weather,
      sample_area = transect_width / 1000 * length_km.y,
      transect_length_km = length_km.y,
      source_name = if_else(
        str_length(input$source) > 0,
        input$source, as.character(NA)
      ),
      pi_credit = if_else(
        str_length(input$pi_credit) > 0,
        input$pi_credit, as.character(NA)
      )
    )
  console_log("make_nppsd.r", "make_tbl_location() end")

  x
}

make_tbl_data_obs <- function(x) {
  console_log("make_nppsd.r", "make_tbl_data_obs() start")
  tdata <- x$transects %>%
    mutate(Date = date(start_time)) %>%
    inner_join(x$nppsd_split, by = c("TripID", "Transect", "Date")) %>%
    transmute(
      master_key = glue(
        "{TripID}_",
        "{str_pad(Transect, 4, pad = '0')}_",
        "{year(start_time.y)}",
        "{sprintf('%02d', month(start_time.y))}",
        "{sprintf('%02d', day(start_time.y))}_",
        "{sprintf('%02d', nppsd_split_id)}"
      ),
      transect_width = as.numeric(gsub("([0-9.]+).*", "\\1", TxWidth)),
      length_km = length_km.y,
      sample_area = transect_width / 1000 * length_km
    ) %>%
    select(-transect_width)

  str_agg <- function(v, collapse_) {
    v <- v[!is.na(v)]
    paste0(v, collapse = collapse_)
  }

  tbl_data_obs <- x$all_obs_data %>%
    mutate(master_key = glue(
      "{TripID}_",
      "{str_pad(Transect, 4, pad = '0')}_",
      "{year(timestamp)}",
      "{sprintf('%02d', month(timestamp))}",
      "{sprintf('%02d', day(timestamp))}_",
      "{sprintf('%02d', nppsd_split_id)}"
    )) %>%
    inner_join(tdata, by = "master_key") %>%
    left_join(
      x$nppsd_species_crosswalk,
      by = c("Species" = "custom_species_code")
    ) %>%
    mutate(
      Species = coalesce(nppsd_species_code, Species)
    ) %>%
    left_join(ref_species_codes, by = c("Species" = "code")) %>%
    transmute(
      master_key = master_key,
      sample_area = sample_area,
      number = as.numeric(Count),
      nppsd_4_letter_code = Species,
      primary_behavior = str_to_title(PrimaryBehavior),
      secondary_behaviory = str_to_title(SecondaryBehavior),
      species_obs_comments = Comments,
      ot_obs = ONOFFTX
    ) %>%
    group_by(
      master_key, sample_area, nppsd_4_letter_code,
      primary_behavior, secondary_behaviory, ot_obs
    ) %>%
    summarize(
      number = sum(number),
      species_obs_comments = unique_str_agg(species_obs_comments),
      .groups = "drop"
    ) %>%
    mutate(density = if_else(ot_obs == "ON", number / sample_area, as.numeric(NA))) %>%
    select(
      master_key, nppsd_4_letter_code,
      primary_behavior, secondary_behaviory,
      number, density,
      ot_obs, species_obs_comments
    )

  x$tbl_data_obs <- tbl_data_obs

  console_log("make_nppsd.r", "make_tbl_data_obs() end")

  x
}
# vim: set ft=r fenc=utf-8 tw=80 ts=2 sw=2 sts=2:
