library(metapsyData)
library(metapsyTools)
library(tidyverse)

d <- getData("gambling-psyctr", version = "24.0.0")
dat <- d$data

# Larimer, 2012 follow-ups are treated as post-test
dat %>% {.[.$study=="Larimer, 2012","time"] = "post";.} -> dat

# Run combined MA for severity
filterPoolingData(
  dat, outcome_domain  == "gambling", time == "post",
  gambling_outcome == "severity") %>%
  runMetaAnalysis(which.run = "combined",
                  rho.within.study = 0.5,
                  which.combine = "arms") %>%
  {.$model.combined$data$N =
    round(.$model.combined$data$n_arm1 +
    .$model.combined$data$n_arm2);
    .$model.combined$data$rob = floor(.$model.combined$data$rob);
  .$model.combined$data} -> severity

# Run combined MA for duration
filterPoolingData(
  dat, outcome_domain  == "gambling", time == "post",
  gambling_outcome == "duration") %>%
  runMetaAnalysis(which.run = "combined",
                  rho.within.study = 0.5,
                  which.combine = "arms") %>%
  {.$model.combined$data$N =
    round(.$model.combined$data$n_arm1 +
    .$model.combined$data$n_arm2);
    .$model.combined$data$rob = floor(.$model.combined$data$rob);
  .$model.combined$data} -> duration

# Run combined MA for frequency
filterPoolingData(
  dat, outcome_domain  == "gambling", time == "post",
  gambling_outcome == "frequency") %>%
  runMetaAnalysis(which.run = "combined",
                  rho.within.study = 0.5,
                  which.combine = "arms") %>%
  {.$model.combined$data$N =
    round(.$model.combined$data$n_arm1 +
    .$model.combined$data$n_arm2);
    .$model.combined$data$rob = floor(.$model.combined$data$rob);
  .$model.combined$data} -> frequency

# Run combined MA for intensity
filterPoolingData(
  dat, outcome_domain  == "gambling", time == "post",
  gambling_outcome == "intensity") %>%
  runMetaAnalysis(which.run = "combined",
                  rho.within.study = 0.5,
                  which.combine = "arms") %>%
  {.$model.combined$data$N =
    round(.$model.combined$data$n_arm1 +
    .$model.combined$data$n_arm2);
    .$model.combined$data$rob = floor(.$model.combined$data$rob);
  .$model.combined$data} -> intensity


# Combine and save
list(severity = severity,
     duration = duration,
     frequency = frequency,
     intensity = intensity,
     metadata = d$returnMetadata()) -> GamblingDB

save(GamblingDB,
     file="www/data/GamblingDB.rda")