#include <cstdio>
#include <cstdlib>
#include <cstdint>
#include <string>
#include <vector>
#include <time.h>

#define NUM_LINES 14

using namespace std;

string httpHeader1 = "HTTP/1.1 200 OK\nContent-Length: ", 
       httpHeader2 = "\nContent-Type: text/html; charset=\"utf-8\"\nConnection: close\n\n",
       htmlTop = "<!DOCTYPE html>\n<html>\n<head>\n<title>Fabulous IBM poem</title>\n<style>\np {line-height: 2.2em;}\n</style>\n</head>\n<body style=\"background: black\">\n",
       htmlBottom = "\n</body>\n</html>",
       pTagStart = "<p>",
       pTagEnd = "</p>\n",
       hTagStart = "<h1>",
       hTagEnd = "</h1><br>",
       spanStart1 = "<span style=\"color: rgb(",
       spanStart2 = ");font-size:",
       spanStart3 = "em\">",
       spanEnd = "</span>";

struct vocabList
{
	string vocabulary[26];
};

struct vocabFileInfo
{
	uint8_t *bufP;
	int bufLen;
};

struct color
{
	uint8_t r, g, b;
};

int vocabFreq[26] = {0};
string pTags[NUM_LINES];
vector<vector<int>*> freqSize;
int ptagsTotalSize = 0;
vector<vector<string>*> lines;
vector<vector<int>*> colorIDs;
color randColors[26];

void read_vocab_file_from_disk(char *filename, vocabFileInfo *info)
{
	FILE *fileHandle = fopen(filename, "rb");

	if (fileHandle == NULL)
	{
		printf("Real funny there, handing me the name of a file that doesn't exist. Almost as funny as a pair of concrete shoes.\n");
		exit(0);
	}

	fseek(fileHandle, 0, SEEK_END);
	info->bufLen = ftell(fileHandle);
	rewind(fileHandle);

	if (info->bufLen == 0)
	{
		printf("Waddah ya doin'! Who do you think you are handin' me an empty file like that? Phil Leotardo? Come on now.\n");
		exit(0);
	}

	info->bufP = (uint8_t*)malloc(sizeof(uint8_t) * info->bufLen);

	fread(info->bufP, sizeof(uint8_t), info->bufLen, fileHandle);

	fclose(fileHandle);
}

vocabList* init_vocab(char *filename)
{
	int letterNum = 0, fileOffset1 = 0, fileOffset2 = 0;
	vocabList *vocab = new vocabList;
	vocabFileInfo info;

	read_vocab_file_from_disk(filename, &info);

	for (int letterNum = 0; letterNum < 26; letterNum++)
	{
		vocab->vocabulary[letterNum] = "";

		if (fileOffset2 >= info.bufLen)
		{
			printf("Hey deadbeat, ya' didn't give me all 26 words I asked for. Do I look like a bitch to you? No? So why ya' tryin' to fuck me like one? They'll be scraping you off the walls if you don't pay me back by next week.\n");
			exit(0);
		}
		else if (info.bufP[fileOffset2] == '\n') 
		{
			printf("Line %d is blank dingus.\n", letterNum + 1);
			exit(0);
		}

		fileOffset1 = fileOffset2;

		while ((info.bufP[fileOffset2] != '\n') && (fileOffset2++ < info.bufLen));
		vocab->vocabulary[letterNum].assign(info.bufP + fileOffset1, info.bufP + fileOffset2);

		// this keeps the \n at the end of each line from being counted as the first character in the next line
		fileOffset2++; 
	}

	free(info.bufP);

	return vocab;
}

vector<string> *expand_word(vocabList *v, string inString, int lineNo)
{
	vector<string> *retStringVec = new vector<string>; int vocabOffset;

	vector<int> *freqsThisLine = new vector<int>;
	vector<int> *colorIdsThisLine = new vector<int>;

	for (int index = 0; index < inString.length(); index++)
	{
		vocabOffset = int(inString.at(index)) - 97;
		if (vocabOffset < 0)
			vocabOffset += 32;
		retStringVec->push_back(v->vocabulary[vocabOffset]);

		freqsThisLine->push_back(++vocabFreq[vocabOffset]);
		colorIdsThisLine->push_back(vocabOffset);
	}

	freqSize.push_back(freqsThisLine);
	colorIDs.push_back(colorIdsThisLine);

	return retStringVec;
}

uint8_t interp(float ratio, uint8_t i)
{
	return 255 - ((255 - i) * ratio);
}

string set_color(int i, int j)
{
	float ratio = float(freqSize.at(i)->at(j)) / 4;

	if (ratio > 1.0f)
		ratio = 1.0f;

	return to_string(interp(ratio, randColors[colorIDs.at(i)->at(j)].r)) + "," + 
	       to_string(interp(ratio, randColors[colorIDs.at(i)->at(j)].g)) + "," +
      	       to_string(interp(ratio, randColors[colorIDs.at(i)->at(j)].b));
}

void generate_ptag(int i)
{
	if (i == 0)
		pTags[i] += hTagStart;
	else 
		pTags[i] += pTagStart;
	for (int j = 0; j < lines.at(i)->size(); j++)
		pTags[i] += spanStart1 + set_color(i, j) + spanStart2 + to_string(2.3f + 0.4f * freqSize.at(i)->at(j)).substr(0, 4) + spanStart3 + lines.at(i)->at(j) + " " + spanEnd;
	if (i == 0)
		pTags[i] += hTagEnd;
	else
		pTags[i] += pTagEnd;

	ptagsTotalSize += pTags[i].length();
}

void init_colors()
{
	srand(time(NULL));

	for (int i = 0; i < 26; i++)
	{
		do 
		{
			randColors[i].r = (rand() % 3) * 127;
			randColors[i].g = (rand() % 3) * 127;
			randColors[i].b = (rand() % 3) * 127;
		}
		while (((randColors[i].r == 0) && (randColors[i].g == 0) && (randColors[i].b == 0)) || ((randColors[i].r == 254) && (randColors[i].g == 254) && (randColors[i].b == 254)));
	}
}

void print_poem(vocabList *v, string seed)
{
	lines.push_back(expand_word(v, seed, 0)); // the title is internally recognized as the "zeroth" line
	generate_ptag(0);


	int sourceLine = 0, persistentWordIndex = 0; 

	for (int i = 1; i < NUM_LINES; i++)
	{
		if (persistentWordIndex == lines.at(sourceLine)->size())
		{
			persistentWordIndex = 0;
			sourceLine++;
		}
		
		lines.push_back(expand_word(v, lines.at(sourceLine)->at(persistentWordIndex++), i));

		generate_ptag(i);
	}

	printf("%s%d%s", httpHeader1.c_str(), htmlTop.length() + ptagsTotalSize + htmlBottom.length(), httpHeader2.c_str());

	printf("%s", htmlTop.c_str());

	for (int i = 0; i < NUM_LINES; i++)
	{
		printf("%s", pTags[i].c_str());

		delete freqSize.at(i);
		delete lines.at(i);
		delete colorIDs.at(i);
	}

	printf("%s", htmlBottom.c_str());

	delete v;
}

int main(int iVar, char** cVar)
{
	if (iVar != 3)
	{
		printf("please furnish two and only two operands, the filename of the vocab list for your IBM poem and its three letter phrase!\n");
		return 0;
	}

	init_colors();
	print_poem(init_vocab(cVar[1]), string(cVar[2]));
}
