library(tidyverse, warn.conflicts = FALSE)
library(DBI, warn.conflicts = FALSE)
library(tidyr, warn.conflicts = FALSE)
library(dplyr, warn.conflicts = FALSE)

HOME <- Sys.getenv("HOME")
Sys.setenv(PGHOST = "db.mainscnt.eu",
           PGDATABASE = "power",
           PGPORT = 5432,
           PGUSER = "wn",
           PGSSLMODE = "verify-ca",
           PGSSLKEY = paste(HOME, "/keys/psql/wn-postgresql-client-2.key", sep=""),
           PGSSLCERT = paste(HOME, "/keys/psql/wn-postgresql-client-2.crt", sep=""),
           PGSSLROOTCERT = paste(HOME, "/keys/psql/postgres-ca.crt", sep=""))


con <- dbConnect(RPostgres::Postgres())

YEAR <- 2022
res <- dbSendQuery(con, "
  select 
          date_trunc('day', time)::date as day,
          avg(temperature) as temperature
      from room_climate_measurement_t
      where
          category = 'Outdoor' and
          location = 'Outdoor' and
          extract('hour' from time) = 12 and
          extract('year' from time) = $1
      group by day
      order by day
")
dbBind(res, list(YEAR))
distribution <- dbFetch(res)
dbClearResult(res)

g <- ggplot(data = distribution, aes(x = temperature)) +
  geom_histogram(binwidth = 1)

print(g)

