/* gnome-chords.c - a free GTK+/GNOME guitar chord finder program

   Copyright (C) 2021 Ole Aamot <ole@gnome.org>

   This program is in the public domain.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <gst/gst.h>
#include "gnome-chords.h"
#include "gnome-chords-console.h"
#include "gnome-chords-mapping.h"

#define PROGRAM "chord"
#define VERSION "0.2.0"

struct Chord *crd;

void chord_text(char *chord, char *lyric)
{
	int key = 0;
	int ret = 0;
	key = getc(stdin);
	ret = chord_play(chord);
	crd->ops->text(lyric);
}

void chord_loop(void)
{
	int i;
	int ret;
	int key;
	key = getc(stdin);
	for (i = 0; cm[i].root; ++i) {
		crd = &cm[i];
		ret = crd->ops->show(cm[i].root,
				     cm[i].e1, cm[i].b2,
				     cm[i].g3, cm[i].d4, 
				     cm[i].a5, cm[i].e6);
		fprintf(stdout, "\tPress ENTER to continue!\n");
		key = getc(stdin);
	}
}

int chord_play(char *chord)
{
	int i;
	int ret = 0;

	for (i = 0; cm[i].root; ++i) {
		if (strcasecmp(chord, cm[i].root))
			continue;

		crd = &cm[i];

		ret =
			crd->ops->show(cm[i].root, 
				       cm[i].e1, cm[i].b2,
				       cm[i].g3, cm[i].d4, 
				       cm[i].a5, cm[i].e6);

		if (ret)
			return ret;
	}

	return ret;
}

static char *chord_read(void)
{
	char *array = (char *)malloc(4);
	fscanf(stdin, "%s", array);
	return array;
}

void chord_prompt(void)
{
	fprintf(stdout, "Enter <name> of the chord (C,G#,Bb,etc.), <loop> or <quit>: ");
	return;
}

void chord_fail(char *buffer)  {
	fprintf(stdout, "Chord %s does not exist\n\nTo add missing chords to the program, please add it in\n\n\t\tgnome-chords/src/gnome-chords-mapping.c\n\nand email the chord name and sample to ole@gnome.org\n\nFile any missing chords at\n\n\t\thttps://gitlab.gnome.org/ole/gnome-chords/-/issues\n\nSee https://www.gingerblue.org/ for recording software.\n\n", buffer);
	return;
}

void chord_main(int argc, char **argv)
{

	char *buffer = NULL;
	int ret;
	gst_init(&argc, &argv);
	if (argc < 2) {
		chord_prompt();
		while (1) {
			buffer = chord_read();
			if (strcasecmp("loop", buffer) == 0) {
				chord_loop();
				chord_prompt();
				free(buffer);
				buffer = chord_read();
			}
			if (strcasecmp("quit", buffer) != 0) {
				ret = chord_play(buffer);
				if (ret != 1) {
					chord_fail(buffer);
				}
				chord_prompt();
				free(buffer);
			} else {
				free(buffer);
				exit(0);
			}
		}
		exit(0);
	} else {
		int ret = chord_play(argv[1]);
		if (ret == 0) chord_fail(argv[1]);
	}
	free(buffer);
	gst_deinit();
	return;
}

int main(int argc, char **argv)
{
	if (argc < 1) {
		fprintf(stdout, "%s (%s)\n\n", PROGRAM, VERSION);
		fprintf(stdout, "%s NAME\n", PROGRAM);
	} else {
		chord_main(argc, argv);
	}
	return 0;
}
