/*
 * main.c
 * 
 * Copyright 2020  <cpp@zom.bi>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 * 
 * 
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <json-c/json_object.h>

#include "lichess.h"
#include "http.h"

int main(int argc, char **argv)
{
	// json_object *profile = malloc(1);
	FILE *output = fopen("output.csv","w");
	FILE *playersfile = fopen("players.csv","r");
	if(playersfile == NULL)
	{
		fputs("Couldn't open players.csv\n",stdout);
		return 1;
	}
	fputs("lichess_id,name\n",output);
	char line [128];
	int j=0;
	while(fgets(line, sizeof line, playersfile) != NULL)
	{
		printf("%i",j);
		j++;
		char outline[256];
		char name[128];
		line[strlen(line)-1] = '\0';
		json_object *profile = query_lichess(line);
		if(profile == NULL)
		{
			printf("No profile for %s\n", line);
			continue;
		}
		char *firstName = json_object_get_string(json_object_object_get(profile,"firstName"));
		char *lastName = json_object_get_string(json_object_object_get(profile,"lastName"));
		if(firstName == NULL || lastName == NULL)
		{
			printf("No name for %s\n",line);
			continue;
		}
		strcpy(name,firstName);
		strcat(name," ");
		strcat(name,lastName);
		sprintf(outline, "%s,%s\n",line,name);
		printf("OK\n");
		fputs(outline,output);
		fclose(output);
		fopen("output.csv","a");
	}
	fclose(output);
	fclose(playersfile);
	return 0;
}