#include <log.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "types.h"

#include "config.h"
#include "config_file.h"
#include "forge.h"
#include "midi.h"
#include "project.h"
#include "shaders.h"
#include "shared.h"
#include "state.h"
#include "tempo.h"
#include "timer.h"
#include "video.h"
#include "window.h"

static Parameters init_params;
static SharedContext *context;
static ShaderProgram program;
static Window *window_output;
static Window *window_monitor;
static Timer timer;
static MidiDevice midi;
static bool trace_midi;
static Project project;

static void compute_fps() {
  double fps;
  char title[STR_LEN];

  if (timer_inc(&timer)) {
    fps = timer_reset(&timer);

    if (init_params.trace_fps) {
      log_trace("(main) %.2ffps", fps);
    }

    if (window_output != NULL) {
      snprintf(title, STR_LEN, PACKAGE " " VERSION " - %.0ffps", fps);
      window_update_title(window_output, title);
    }

    if (window_monitor != NULL) {
      snprintf(title, STR_LEN, PACKAGE " " VERSION " (monitor) - %.0ffps", fps);
      window_update_title(window_monitor, title);
    }

    context->fps = (unsigned int)round(fps);
  }
}

static void init_context() {
  context = shared_init_context("/" PACKAGE "_context");

  context->stop = false;

  state_init(context, &project.state_config, init_params.demo,
             init_params.auto_random, init_params.auto_random_cycle,
             init_params.base_tempo, init_params.load_state);

  memset(context->input_resolutions, 0, sizeof(context->input_resolutions));
}

static void free_context() { shared_close_context(context); }

static void reload_shader(unsigned int i) {
  shaders_update(&program, &project.fragment_shaders[i][0], i, &project);
}

#ifdef VIDEO_IN
static void init_inputs() {
  context->inputs.length = init_params.video_in.length;

  for (unsigned int i = 0; i < init_params.video_in.length; i++) {
    video_init(&context->inputs.values[i], init_params.video_in.values[i],
               init_params.video_size);

    if (!context->inputs.values[i].error) {
      context->input_resolutions[i][0] = context->inputs.values[i].width;
      context->input_resolutions[i][1] = context->inputs.values[i].height;
      context->inputs.values[i].needs_reload = false;
      context->inputs.values[i].disconnected = false;
    }
  }
}

static bool reconnect_video_captures() {
  for (unsigned int i = 0; i < init_params.video_in.length; i++) {
    if (context->inputs.values[i].disconnected) {
      video_init(&context->inputs.values[i], init_params.video_in.values[i],
                 init_params.video_size);

      if (!context->inputs.values[i].error) {
        context->input_resolutions[i][0] = context->inputs.values[i].width;
        context->input_resolutions[i][1] = context->inputs.values[i].height;

        if (!video_background_read(&context->inputs.values[i], context, i,
                                   init_params.trace_fps)) {
          return false;
        }

        context->inputs.values[i].needs_reload = true;
        context->inputs.values[i].disconnected = false;
      }
    }
  }
  return true;
}

static bool start_video_captures() {
  pid_t pid;
  for (unsigned int i = 0; i < context->inputs.length; i++) {
    if (!context->inputs.values[i].error &&
        !video_background_read(&context->inputs.values[i], context, i,
                               init_params.trace_fps)) {
      return false;
    }
  }
  if (!init_params.video_reconnect) {
    return true;
  }
  pid = fork();
  if (pid < 0) {
    log_error("Could not create subprocess");
    return false;
  }
  if (pid == 0) {
    return true;
  }
  log_info("background reconnect acquisition started (pid: %d)", pid);
  while (!context->stop) {
    sleep(1);
    if (!reconnect_video_captures()) {
      return false;
    }
  }
  exit(EXIT_SUCCESS);
}

static void free_video_captures() {
  for (unsigned int i = 0; i < context->inputs.length; i++) {
    shaders_free_input(&program, i);

    video_free(&context->inputs.values[i]);
  }
}

#endif /* VIDEO_IN */

static void error_callback(int error, const char *description) {
  log_error("[GLFW] %d: %s", error, description);
  window_terminate();
  context->stop = true;
  exit(EXIT_FAILURE);
}

static void key_callback(Window *window, int key,
                         __attribute__((unused)) int scancode, int action,
                         int mods) {
  unsigned int event;

  event = window_read_key(key, action, mods);

  if (window_escape_key(key, action)) {
    // close window on escape key
    log_info("[ESC] Closing...");
    window_close(window);
  } else if (event > 0) {
    state_key_event(context, &project.state_config, event, &midi);
  }
}

static void midi_callback(unsigned char code, unsigned char value) {
  state_midi_event(context, &project.state_config, &midi, code, value,
                   trace_midi);
}

static bool init(const Parameters *params) {
  init_params = *params;

  project_init(&project, params->project_path, params->config_file);

  if (project.error) {
    return false;
  }

  init_context();

#ifdef VIDEO_IN
  init_inputs();

  if (!start_video_captures()) {
    return false;
  }
#endif /* VIDEO_IN */

  midi_open(&midi, config_file_get_str(&project.config, "MIDI_HW", "hw"));

  if (midi.error) {
    context->demo = true;
  } else {
    trace_midi = params->trace_midi;

    if (!midi_background_listen(&midi, context, midi_callback)) {
      return false;
    }
  }

  if (!state_background_write(context, &project.state_config, &midi)) {
    return false;
  }

  window_startup(error_callback);

  context->tex_resolution[1] = params->internal_size;

  if (params->output) {
    window_output = window_init(PACKAGE " " VERSION, params->output_screen,
                                params->windowed, NULL, key_callback);

    window_use(window_output, context);

    shaders_init(&program, &project, context, false);
  } else {
    window_output = NULL;
  }

  if (params->monitor) {
    window_monitor =
        window_init(PACKAGE " " VERSION " (monitor)", params->monitor_screen,
                    params->windowed, window_output, key_callback);

    window_use(window_monitor, context);

    shaders_init(&program, &project, context, window_output != NULL);
  } else {
    window_monitor = NULL;
  }

#ifdef VIDEO_IN
  shaders_link_inputs(&program, &project, &context->inputs);
#endif /* VIDEO_IN */

  if (program.error) {
    context->stop = true;
    window_terminate();
    exit(EXIT_FAILURE);
  }

  timer_init(&timer, 30);

  log_info("Initialized");

  return true;
}

static bool should_close() {
  return (window_output != NULL && window_should_close(window_output)) ||
         (window_monitor != NULL && window_should_close(window_monitor));
}

static bool loop() {
  if (init_params.hot_reload) {
    project_reload(&project, reload_shader);
  }

#ifdef VIDEO_IN
  if (init_params.video_reconnect) {
    for (unsigned int i = 0; i < context->inputs.length; i++) {
      if (context->inputs.values[i].needs_reload) {
        shaders_relink_input(&program, &project, &context->inputs, i);
        context->inputs.values[i].needs_reload = false;
      }
    }
  }
#endif /* VIDEO_IN */

  compute_fps();

  context->time = window_get_time();
  context->tempo_total = (float)tempo_total(&context->tempo);

  if (window_output != NULL) {
    window_use(window_output, context);

    shaders_compute(&program, context, false, false);

    window_refresh(window_output);
  }

  if (window_monitor != NULL) {
    window_use(window_monitor, context);

    shaders_compute(&program, context, true, window_output != NULL);

    window_refresh(window_monitor);
  }

  window_events();

  return true;
}

static void shutdown() {
  context->stop = true;

  if (init_params.save_state) {
    state_save(context, &project.state_config);
  }

  shaders_free(&program);

  if (window_output != NULL) {
    window_use(window_output, context);

    shaders_free_window(&program, false);
  }

  if (window_monitor != NULL) {
    window_use(window_monitor, context);

    shaders_free_window(&program, init_params.output);
  }

#ifdef VIDEO_IN
  free_video_captures();
#endif /* VIDEO_IN */

  free_context();

  project_free(&project);

  window_terminate();
}

void forge_run(const Parameters *params) {
  if (!init(params)) {
    return;
  }

  while (!should_close()) {
    if (!loop()) {
      return;
    }
  }

  shutdown();
}
