#include <errno.h>
#include <csignal>
#include "color.h"
#include <iostream>
#include "exitcleanup.hpp"
#include "types.hpp"
#include "main.hpp"

void SignalHandler(int code) {
    switch (code) {
      case SIGTERM:
        std::cerr << "\nreceived SIGTERM exiting...\n";
        break;
      case SIGINT:
        std::cerr << "\nreceived SIGINT exiting...\n";
        break;
      case SIGQUIT:
        std::cerr << "\nreceived SIGQUIT exiting...\n";
        break;
      case SIGHUP:
        std::cerr << "\nreceived SIGHUP exiting...\n";
        break;
    
      case SIGSEGV:
        std::cerr << "\nreceived SIGSEGV(segmentaiton fault) exiting...\nIf this "
                     "repeats please report it as a bug\n";
        break;
    }
    try {
      GeneralCleanUp(code);
    } catch(...) {
      std::cerr << RED"[ERROR]" << RESET" general cleanup error\n";
      exit(errno);
    }
  }
  
  void GeneralCleanUp(int code) {
  
    for(Entity *entity : loaded_entities) {
      try {
      SDL_DestroyTexture(entity->texture);
      } catch(...) {
        std::cerr << RED"[ERROR]" << RESET" failed to destroy texture of entity\nentity address:" << YELLOW << entity << RESET"\n";
      }
    }
  
    try {
    SDL_DestroyWindow(main_sdl_session.window);
    } catch(...) {
      std::cerr << RED"[ERROR]" << RESET" failed to destroy window\n";
    }
    try{
    SDL_DestroyRenderer(main_sdl_session.renderer);
    } catch(...) {
      std::cerr << RED"[ERROR]" << RESET" failed to destroy renderer\n";
    }
    try {
    SDL_Quit();
    } catch (...) {
      std::cerr << RED"[ERROR]" << RESET" failed to quit sdl\n";
    } 
    exit(code);
  }