#include <iostream>
#include <conio.h>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <thread>
#include <chrono>
#include <Windows.h>
#include "City.h"
#include "Human.h"
#include "Organism.h"
#include "Zombie.h"
using namespace std;

//Variables
int numberOfHumans = 0;
int numberOfZombies = 0;
int iterations = 0;
City *city = new City();
HANDLE  color = GetStdHandle(STD_OUTPUT_HANDLE);

void runTurnStep()
{
	city->move();
	numberOfHumans = city->numberOfHumans();
	numberOfZombies = city->numberOfZombies();
	iterations++;

	//Draws the board
	cout << *city;
	
	cout << endl;
	SetConsoleTextAttribute(color, 7);
	cout << "Days: " << iterations << endl;
	SetConsoleTextAttribute(color, 2);
	cout << "Humans Left: " << numberOfHumans << endl;
	SetConsoleTextAttribute(color, 4);
	cout << "Zombies Left: " << numberOfZombies << endl;
	SetConsoleTextAttribute(color, BOARD_COLOR);

}



int main()
{
	//random generator seeded with the time
	srand(time(NULL)); 

	do {
		//makes random coordinates
		int ranX = rand() % GRID_WIDTH;
		int ranY = rand() % GRID_HEIGHT;

		int randomSpawn = rand() % 4;

		if (city->getOrganism(ranX, ranY) == NULL) {
			//creates humans
			Human *myHuman = new Human(city, GRID_WIDTH, GRID_HEIGHT);
			myHuman->setPosition(ranX, ranY);
			myHuman->setSpawnCount(randomSpawn);
			city->setOrganism(myHuman, ranX, ranY);
			numberOfHumans++;
		}

	} while (numberOfHumans < HUMAN_STARTCOUNT);

	
	do {
		int ranX = rand() % GRID_WIDTH;
		int ranY = rand() % GRID_HEIGHT;
		int randomSpawn = rand() % 9;

		if (city->getOrganism(ranX, ranY) == NULL) {
			//creates zombies 
			Zombie *myZombie = new Zombie(city, GRID_WIDTH, GRID_HEIGHT);
			myZombie->setPosition(ranX, ranY);
			myZombie->setSpawnCount(randomSpawn);
			city->setOrganism(myZombie, ranX, ranY);
			numberOfZombies++;
		}

	} while (numberOfZombies < ZOMBIE_STARTCOUNT);

	while (numberOfHumans > 0 && numberOfZombies > 0){
		runTurnStep();

		//Uses a timer to iterate through steps
		int timerFAST = 500;
		int timerSlow = 2500;
		int timerLAGGING = 5000;
		clock_t start_time = clock();
		clock_t end_time = PAUSE_SECONDS * timerFAST + start_time;
		//clock_t end_time = PAUSE_SECONDS * timerSLOW + start_time;
		//clock_t end_time = PAUSE_SECONDS * timerLAGGING + start_time;
		while (clock() < end_time);
	}

	//if there are no humans or zombies left
	if (numberOfHumans > 0) { 

		cout << "Humans Win!"; 
	}
	else { 

		cout << "Zombies Win!"; 
	}

	_getch();
	return 0;
}