library(metapsyData)
library(metapsyTools) # v1.0.10
library(metafor)
library(esc)
library(dplyr)

d <- getData("suicide-psyctr", version = "23.1.1")
dat <- d$data

# Run combined MA for ideation outcome data
filterPoolingData(dat, outcome_type  == "ideation") %>%
  runMetaAnalysis(which.run = "combined",
                  rho.within.study = 0.5,
                  which.combine = "arms") %>%
  {.$model.combined$data$N =
    .$model.combined$data$n_arm1 +
    .$model.combined$data$n_arm2;
    .$model.combined$data$year =
      round(as.numeric(gsub("\\D", "", .$model.combined$data$study)));
    .$model.combined$data} %>%
    mutate(year = ifelse(year %in% c(20041, 20042), 2014, year)) %>%
    mutate(year = ifelse(year %in% c(20191, 20192), 2019, year),
           .TE = .TE*-1) -> ideation

# Run combined MA for attempts outcome data
filterPoolingData(dat, outcome_type  == "attempts") %>%
  mutate(log_or = log(((event_arm1+.5)/(totaln_arm1-event_arm1+.5))/
                      ((event_arm2+.5)/(totaln_arm2-event_arm2+.5))),
         se_log_or = sqrt( (1/(event_arm1+.5)) + (1/(totaln_arm1-event_arm1+.5)) +
                           (1/(event_arm2+.5)) + (1/(totaln_arm2-event_arm2+.5)))
) -> dat.attempts

# Convert log-or to g using Chinn method
dat.attempts$.d =
    metafor::conv.delta(dat.attempts$log_or, dat.attempts$se_log_or^2,
                        transf = metafor::transf.lnortod.logis)[,"yi"]
dat.attempts$.g_se =
    metafor::conv.delta(dat.attempts$log_or, dat.attempts$se_log_or^2,
                        transf = metafor::transf.lnortod.logis)[,"vi"] %>% sqrt()
dat.attempts$.g =
    esc::hedges_g(dat.attempts$.d,
                  dat.attempts$totaln_arm1 + dat.attempts$totaln_arm2)

dat.attempts %>%
  select(-.d, -log_or, -se_log_or) %>%
  runMetaAnalysis(which.run = "combined",
                  rho.within.study = 0.5,
                  which.combine = "arms") %>%
  {.$model.combined$data$N =
    .$model.combined$data$totaln_arm1 +
    .$model.combined$data$totaln_arm2;
    .$model.combined$data$year =
      round(as.numeric(gsub("\\D", "",
      .$model.combined$data$study)));
    .$model.combined$data} %>%
    mutate(year = ifelse(year %in% c(20041, 20042), 2014, year)) %>%
    mutate(year = ifelse(year %in% c(20191, 20192), 2019, year),
           .TE = .TE*-1) -> attempts

# Combine and save
list(ideation = ideation, attempts = attempts,
     metadata = d$returnMetadata()) -> SuicideDB

save(SuicideDB, file="www/SuicideDB.rda")