```{r setup,eval=TRUE,echo=FALSE}
if (!exists("indent")) {
	indent <- '#' # ugly hack so _regression_summary can be "spun" (variables included via `r ` have to be available)
}
if (exists("testing")) {
	item <- 1:10
	item_name <- "yay"
	attributes(item) <- list(label = 'yayya')
}
item_attributes <- attributes(item)
item_label <- ifelse(is.null(item_attributes) || is.null(item_attributes$label), 
                     "", item_attributes$label)
item_info <- item_attributes$item
choices <- item_attributes$labels
```

`r indent`## `r item_name` {#`r item_name` .tabset}

`r item_label`

`r indent`### Distribution {#`r item_name`_distribution}
```{r setup_missings}
show_missings <- FALSE
if (haven::is.labelled(item)) {
  missings <- item[is.na(haven::zap_missing(item))]
  if (is.numeric(item)) {
    show_missings <- length(unique(haven::na_tag(missings))) > 1
    item <- haven::zap_missing(item)
  }
  if (length(attributes(item)$labels) == 0 && is.numeric(item)) {
    item <- haven::zap_labels(item)
  }
}
old_height <- knitr::opts_chunk$get("fig.height")
non_missing_choices <- attributes(item)[["labels"]]
many_labels <- length(non_missing_choices) > 7
go_vertical <- !is.numeric(item) || many_labels
if ( go_vertical ) {
  # numeric items are plotted horizontally (because that's what usually expected)
  # categorical items are plotted vertically because we can use the screen real estate better this way

	if (is.null(choices) || 
	    dplyr::n_distinct(na.omit(item)) > length(non_missing_choices)) {
		choices <- unique(na.omit(item))
		names(choices) <- choices
		non_missing_choices <- choices
	}
  choice_multiplier <- old_height/6.5
	new_height <- 2 + choice_multiplier * length(non_missing_choices)
	new_height <- ifelse(new_height > 20, 20, new_height)
	new_height <- ifelse(new_height < 1, 1, new_height)
	knitr::opts_chunk$set(fig.height = new_height)
}

wrap_at <- knitr::opts_chunk$get("fig.width") * 10
```
```{r distribution}
# todo: if there are free-text choices mingled in with the pre-defined ones, don't show
# todo: show rare items if they are pre-defined
# todo: bin rare responses into "other category"

if (is.numeric(item) || dplyr::n_distinct(item) < 20) {
  attribs <- attributes(item)
  item <- item[!is.na(item)]
  attributes(item) <- attribs
  plot_labelled(item, item_name, wrap_at, go_vertical)
} else {
	cat(dplyr::n_distinct(item), " unique, categorical values, so not shown.")
}
knitr::opts_chunk$set(fig.height = old_height)
```

`r sum(is.na(item))` missings.

`r indent`### Summary statistics {#`r item_name`_summary}
```{r summary}
df = data.frame(item)
names(df) = item_name
pander::pander(codebook_table(df))
```

`r ifelse(show_missings, paste0(indent, '### Missing value types {#', item_name, '_missings}'), '')`
```{r}
if (show_missings) {
  plot_labelled(missings, item_name, wrap_at)
}
```

`r ifelse(!is.null(item_info), paste0(indent, '### Item {#', item_name, '_item}'), '')`

```{r items}
if (!is.null(item_info)) {
  item_info$label_parsed <- item_info$choices <- 
    item_info$choice_list <- item_info$study_id <- item_info$id <- NULL
  pander::pander(as.data.frame(t(item_info)))
}
```


`r ifelse(!is.null(choices) && length(choices) < 30, paste0(indent, '### Value labels {#', item_name, '_labels}'), '')`
```{r choices}
if (!is.null(choices) && length(choices) < 30) {
	pander::pander(as.list(choices))
}
```

