
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include "Main.h"
#include "Common.h"
#include "World.h"
#include "glm/glm.hpp"
#include "glm/ext.hpp"
#include "ResourceManager.h"
#include "Scene.h"
#include "Object.h"

#ifdef _DEBUG
#else
#pragma comment(lib, "glfw3.lib")
#pragma comment(lib, "glew32.lib")
#endif

#pragma comment(lib, "opengl32.lib")

//ウィンドウ
GLFWwindow *pWindow;

//プレイヤー
Player *pPlayer;

//プレイヤーの弾
PlayerBullet *pBullet;

//敵
Enemy *pEnemy;

int main(int argc, char *argv[]) {
	
	glfwSetErrorCallback(ErrorCallback);
	
	if( !glfwInit() ) {
		std::cerr << "glfwInit failed" << std::endl;
		return 1;
	}
	
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
	
	pWindow = glfwCreateWindow(
		SCREEN_WIDTH, SCREEN_HEIGHT, "GLShooting", nullptr, nullptr
	);
	if( !pWindow ) {
		std::cerr << "glfwCreateWindow failed" << std::endl;
		return 1;
	}
	
	glfwMakeContextCurrent(pWindow);
	glfwSwapInterval(1);
	glfwSetFramebufferSizeCallback(pWindow, FramebufferResizeCallback);
	
	glewExperimental = GL_TRUE;
	if( glewInit() != GLEW_OK ) {
		std::cerr << "glewInit failed" << std::endl;
		return 1;
	}
	
	//ortho行列を登録
	glm::mat4 matOrtho =
		glm::ortho(0.0f, (float)SCREEN_WIDTH, 0.0f, (float)SCREEN_HEIGHT);
	glMatrixMode(GL_PROJECTION);
	glLoadMatrixf(&matOrtho[0][0]);
	
	//半透明を有効
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	
	pResMngr = new ResourceManager();
	
	try {
		Init();
		while( !glfwWindowShouldClose(pWindow) ) {
			Update();
			Draw();
			glfwSwapBuffers(pWindow);
			glfwPollEvents();
		}
		
	} catch( std::exception &e ) {
		std::cerr << e.what() << std::endl;
		getchar();
	}
	
	glfwTerminate();
	
	delete pPlayer;
	delete pEnemy;
	
	return 0;
	
}

void ErrorCallback(int error, const char *msg) {
	std::cerr << "GLFW error callback\n";
	std::cerr << msg << std::endl;
}

void FramebufferResizeCallback(GLFWwindow *pWindow, int width, int height) {
	glViewport(0, 0, width, height);
}

void Init() {
	pPlayer = new Player(pWindow);
	pPlayer->SetPosition(glm::vec2(SCREEN_WIDTH * 0.5f, 20.0f));
	
	pBullet = new PlayerBullet();
	pBullet->SetPosition(pPlayer->GetPosition());
	pBullet->SetVelocity(glm::vec2(0.0f, 6.0f));
	
	pEnemy = new Enemy();
	pEnemy->SetPosition(glm::vec2(
		SCREEN_WIDTH * 0.5f, SCREEN_HEIGHT
	));
	pEnemy->SetVelocity(glm::vec2(0.0f, -2.0f));
}

void Update() {
	//画面クリア
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glClear(GL_COLOR_BUFFER_BIT);
	
	pPlayer->Update();
	pEnemy->Update();
	pBullet->Update();
	
}

void Draw() {
	pPlayer->Draw();
	pEnemy->Draw();
	pBullet->Draw();
}


