#include <log.h>
#include <math.h>
#include <pthread.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 "state.h"
#include "tempo.h"
#include "timer.h"
#include "video.h"
#include "window.h"

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

#ifdef VIDEO_IN
static VideoCaptureArray video_captures;
#endif /* VIDEO_IN */

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.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);

#ifdef VIDEO_IN
  memset(context.input_resolutions, 0, sizeof(context.input_resolutions));
  memset(context.input_formats, 0, sizeof(context.input_formats));
  memset(context.input_fps, 0, sizeof(context.input_fps));
  memset(context.input_swap, 0, sizeof(context.input_swap));
#endif /* VIDEO_IN */
}

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

#ifdef VIDEO_IN

static void init_inputs() {
  video_captures.length = init_params.video_in.length;

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

    if (!video_captures.values[i].error) {
      context.input_resolutions[i][0] = video_captures.values[i].width;
      context.input_resolutions[i][1] = video_captures.values[i].height;
      context.input_formats[i] = video_captures.values[i].pixelformat;
      video_captures.values[i].needs_reload = false;
      video_captures.values[i].disconnected = false;
    }
  }
}

static void start_video_background_read(VideoCapture *video_capture,
                                        Context *context, int input_index,
                                        bool trace_fps) {
  pthread_t thread;
  struct VideoBackgroundReadArgs *process_args =
      (struct VideoBackgroundReadArgs *)malloc(
          sizeof(struct VideoBackgroundReadArgs));
  process_args->capture = video_capture;
  process_args->context = context;
  process_args->input_index = input_index;
  process_args->trace_fps = trace_fps;
  pthread_create(&thread, NULL, video_background_read, (void *)process_args);
  pthread_detach(thread);
}

static void *
background_reconnect_video_captures(__attribute__((unused)) void *args) {
  log_info("background video capture reconnect started");
  while (!context.stop) {
    sleep(1);
    for (unsigned int i = 0; i < init_params.video_in.length; i++) {
      if (video_captures.values[i].disconnected) {
        video_free(&video_captures.values[i]);
        video_init(&video_captures.values[i], init_params.video_in.values[i],
                   init_params.video_size);

        if (!video_captures.values[i].error) {
          context.input_resolutions[i][0] = video_captures.values[i].width;
          context.input_resolutions[i][1] = video_captures.values[i].height;
          context.input_formats[i] = video_captures.values[i].pixelformat;
          video_captures.values[i].needs_reload = true;
          video_captures.values[i].disconnected = false;
          start_video_background_read(&video_captures.values[i], &context, i,
                                      init_params.trace_fps);
        }
      }
    }
  }
  pthread_exit(NULL);
}

static void start_video_captures() {
  pthread_t thread;
  for (unsigned int i = 0; i < video_captures.length; i++) {
    if (!video_captures.values[i].error) {
      start_video_background_read(&video_captures.values[i], &context, i,
                                  init_params.trace_fps);
    }
  }
  if (init_params.video_reconnect) {
    pthread_create(&thread, NULL, background_reconnect_video_captures, NULL);
    pthread_detach(thread);
  }
}

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

    video_free(&video_captures.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,
                   init_params.trace_midi);
}

static void start_state_background_write() {
  pthread_t thread;
  struct StateBackgroundWriteArgs *process_args =
      (struct StateBackgroundWriteArgs *)malloc(
          sizeof(struct StateBackgroundWriteArgs));
  process_args->context = &context;
  process_args->state_config = project.state_config;
  process_args->midi = &midi;
  pthread_create(&thread, NULL, state_background_write, process_args);
  pthread_detach(thread);
}

static void start_midi_background_listen() {
  pthread_t thread;
  struct MidiBackgroundListenArgs *process_args =
      (struct MidiBackgroundListenArgs *)malloc(
          sizeof(struct MidiBackgroundListenArgs));
  process_args->device = &midi;
  process_args->context = &context;
  process_args->event_callback = midi_callback;
  pthread_create(&thread, NULL, midi_background_listen, process_args);
  pthread_detach(thread);
}

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();

  start_video_captures();
#endif /* VIDEO_IN */

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

  if (midi.error) {
    context.demo = true;
  } else {
    start_midi_background_listen();
  }

  start_state_background_write();

  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, &video_captures);
#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 < video_captures.length; i++) {
      if (video_captures.values[i].needs_reload) {
        shaders_relink_input(&program, &project, &video_captures, i);
        video_captures.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 */

  project_free(&project);

  window_terminate();
}

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

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

  shutdown();
}
