/*
 * main.cpp
 *
 *  Created on: Feb 9, 2020
 *      Author: ayoungblood
 */

#include "Game.hpp"
#include "../cjson/cJSON.h"
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>

Game *game = nullptr;

int main(int argc, const char * argv[])
{
	const int FPS = 60;
	const int frameDelay = 1000 / FPS;

	Uint64 frameStart;
	int frameTime;

//      =============================
//      Load cJSON config.json file
//      =============================
// Starting with Error Checking    
    std::string configPath = "src/config/config.json";
    std::ifstream fin(configPath);
    
    if(fin.is_open()){
        std::ifstream jsonText("src/config/config.json");
        std::ostringstream tmp;
        tmp << jsonText.rdbuf();
        std::string json = tmp.str();
        cJSON * myJSON = cJSON_Parse(json.c_str());
        cJSON * windowName = cJSON_GetObjectItemCaseSensitive(myJSON, "WindowName");
        cJSON * windowSize = cJSON_GetObjectItem(myJSON, "WindowSize");
        int windowWidth = cJSON_GetObjectItem(windowSize, "w")->valueint;
        int windowHeight = cJSON_GetObjectItem(windowSize, "h")->valueint;
        int windowFS = cJSON_GetObjectItem(myJSON, "WindowFullScreen")->valueint;
        int globalScale = cJSON_GetObjectItem(myJSON, "GlobalScale")->valueint;
        bool isWindowFS;
        if (windowFS==0)
        {
        	isWindowFS = false;
        } else
        {
        	isWindowFS = true;
        }
        windowWidth = windowWidth*globalScale;
        windowHeight = windowHeight*globalScale;
	game = new Game();
	game->init(windowName->valuestring, windowWidth, windowHeight, isWindowFS, globalScale);
//	cJSON memory management
    cJSON_Delete(myJSON);

	while (game->running())
	{
		frameStart = SDL_GetTicks64();

		game->handleEvents();
		game->update();
		game->render();

		frameTime = SDL_GetTicks64() - frameStart;

		if(frameDelay > frameTime)
		{
			SDL_Delay(frameDelay - frameTime);
		}

	}
	game->clean();
    } else {
        std::cout<<"config.json not found or opened"<<std::endl;
    }
    
    if(fin.fail()){
        std::cout<<"config.json load failed"<<std::endl;
    } 
        
	return 0;
}
