#include "ui_text_window.h"

#include <pebble.h>

#define TITLE_HEIGHT 30

typedef struct {
  char *title;
  char *body;
  TextLayer *title_layer;
  ScrollLayer *scroll_layer;
  TextLayer *body_layer;
} TextWindowState;

static void window_load(Window *window) {
  TextWindowState *state = window_get_user_data(window);
  Layer *window_layer = window_get_root_layer(window);
  GRect bounds = layer_get_bounds(window_layer);

  state->title_layer = text_layer_create(GRect(0, 0, bounds.size.w, TITLE_HEIGHT));
  text_layer_set_font(state->title_layer, fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD));
  text_layer_set_text(state->title_layer, state->title);
  text_layer_set_overflow_mode(state->title_layer, GTextOverflowModeTrailingEllipsis);
  layer_add_child(window_layer, text_layer_get_layer(state->title_layer));

  GRect scroll_bounds = GRect(0, TITLE_HEIGHT, bounds.size.w, bounds.size.h - TITLE_HEIGHT);
  state->scroll_layer = scroll_layer_create(scroll_bounds);
  scroll_layer_set_click_config_onto_window(state->scroll_layer, window);

  /* Tall placeholder height so text_layer_get_content_size() below can
   * measure the real wrapped height - standard Pebble ScrollLayer
   * pattern (a TextLayer taller than its content just clips nothing). */
  state->body_layer = text_layer_create(GRect(0, 0, scroll_bounds.size.w, 2000));
  text_layer_set_font(state->body_layer, fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD));
  text_layer_set_text(state->body_layer, state->body);
  text_layer_set_overflow_mode(state->body_layer, GTextOverflowModeWordWrap);

  GSize content_size = text_layer_get_content_size(state->body_layer);
  content_size.w = scroll_bounds.size.w;
  content_size.h += 4;
  text_layer_set_size(state->body_layer, content_size);
  scroll_layer_set_content_size(state->scroll_layer, content_size);

  scroll_layer_add_child(state->scroll_layer, text_layer_get_layer(state->body_layer));
  layer_add_child(window_layer, scroll_layer_get_layer(state->scroll_layer));
}

static void window_unload(Window *window) {
  TextWindowState *state = window_get_user_data(window);
  text_layer_destroy(state->title_layer);
  text_layer_destroy(state->body_layer);
  scroll_layer_destroy(state->scroll_layer);
  free(state->title);
  free(state->body);
  free(state);
  window_destroy(window);
}

void text_window_push(const char *title, const char *body) {
  TextWindowState *state = malloc(sizeof(TextWindowState));
  memset(state, 0, sizeof *state);
  state->title = malloc(strlen(title) + 1);
  strcpy(state->title, title);
  state->body = malloc(strlen(body) + 1);
  strcpy(state->body, body);

  Window *window = window_create();
  window_set_user_data(window, state);
  window_set_window_handlers(window, (WindowHandlers){
    .load = window_load,
    .unload = window_unload,
  });
  window_stack_push(window, true);
}
