#include <asm-generic/errno-base.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdarg.h>
#include <linux/input.h>
#include <linux/uinput.h>
#include <linux/input-event-codes.h>

#define BITS_PER_LONG (sizeof(unsigned long) * 8)
#define TEST_BIT(bit, array) \
    (((array)[(bit) / BITS_PER_LONG] >> ((bit) % BITS_PER_LONG)) & 1UL)

void error(char *t,char *m,...)
{
	va_list args;
	va_start(args,m);
	fprintf(stderr, "\033[1;31m[E]\033[0m \033[1;33m%s\033[0m:", t);
	vfprintf(stderr, m,args);
	fprintf(stderr, "\n");
	va_end(args);
	exit(1);
}

struct dirent *entry;
struct input_event ev;

typedef struct {
	int fd;
	int keys[KEY_MAX + 1];
} kb_args;

typedef struct {
	char *Key;
	char *value;
}KeyValue ;

typedef struct {
	KeyValue *items;
	int count;
} Section;

typedef struct {
	Section macro;
	Section block;
	Section repeat;
} Config;




Config *init_config()
{
	Config *list = malloc(sizeof(Config));
	list->macro.items  = malloc(sizeof(KeyValue)); 
	list->block.items  = malloc(sizeof(KeyValue));
	list->repeat.items = malloc(sizeof(KeyValue));
	list->macro.count  = 0; 
	list->block.count  = 0;
	list->repeat.count = 0;
	
	return list;
}

void add_config(Section *cfg,char *key,char *value)
{
	cfg->count++;
	cfg->items = realloc(cfg->items,sizeof(KeyValue) * cfg->count); 
	if (!cfg->items) error("Memory","memory allocation failed.");

	cfg->items[cfg->count -1].Key   = strdup(key);
	cfg->items[cfg->count -1].value = strdup(value);
}

void free_cfg(Config *cfg)
{
	Section *sections[] = {&cfg->macro,&cfg->block,&cfg->repeat};
	for (int i=0;i<3;++i){
		for (int j=0; j< sections[i]->count;++j) {
			free(sections[i]->items[j].Key);
			free(sections[i]->items[j].value);
		}
		free(sections[i]->items);
	}
	free(cfg);
}


int is_keyboard(struct dirent *entry, int *fd, char *full_entry,char *device)
{
		if (strncmp(entry->d_name, "event",5) != 0)  return 0;
		sprintf(full_entry,"/dev/input/%s",entry->d_name);
		if ((*fd=open(full_entry, O_RDONLY)) < 0) return 0;

		unsigned long keybits[(KEY_MAX + BITS_PER_LONG) / BITS_PER_LONG];
		memset(keybits, 0, sizeof(keybits));
		ioctl(*fd,EVIOCGBIT(EV_KEY, sizeof(keybits)),keybits);

		if (	
				!TEST_BIT(KEY_SPACE,keybits)  &&
				!TEST_BIT(KEY_BRIGHTNESS_AUTO, keybits) &&
				!TEST_BIT(KEY_VIDEO, keybits) && 
				!TEST_BIT(KEY_BLUETOOTH, keybits)
			) return 0;

		if (ioctl(*fd, EVIOCGNAME(256), device) < 0) return 0;

		return 1;
}
int remove_spaces(char *str) {
    int j = 0, h = 0;
    for (int i = 0; str[i]; i++) {
        if (!isspace(str[i]) || str[i] == '\n') {
            if (!isspace(str[i])) h = 1;
            str[j++] = str[i];
        }
    }
    str[j] = '\0';
    return h;
}

void read_config(Config *cfg)
{
	FILE *config_file;
	char *config_path = getenv("STA");
	if (!config_path) error("Config", "can not find config path (check man page)");

	if(!(config_file=fopen(config_path,"r")))
	{
        if (errno == ENOENT) error("config","File does not exist");
		if (errno == EISDIR)  error("config","Is a directory");
        if (errno == EACCES) error("config","Permission denied");
    }

	
    char buf[256];
	char header;

	int a = 0;
    while (fgets(buf, sizeof(buf), config_file)) {
		++a;

		if (buf[0]=='#') continue;
		if (!remove_spaces(buf)) continue;

		if (!strncmp(buf,">",1)){
			switch (buf[1]) {
				case 'm': header = 'm'; break;
				case 'b': header = 'b'; break;
				case 'r': header = 'r'; break;
			}
			continue;
		}

		char *spliter = strchr(buf, '=');
		if (!spliter) error("config","syntax error in line %d",a);

		*spliter = '\0';
		char *key = buf;
		char *value = spliter + 1;

		switch (header) {
			case 'm': add_config(&cfg->macro , key, value); break;
			case 'b': add_config(&cfg->block , key, value); break;
			case 'r': add_config(&cfg->repeat, key, value); break;
		}



    }
}

void *keyboard_loop(void *arg)
{
	
    kb_args *kb = arg;
	while (read(kb->fd, &ev, sizeof(ev))) {
		if (ev.type == EV_KEY) {
			kb->keys[ev.code] = ev.value;
			if (kb->keys[KEY_SPACE] >= 1 && kb->keys[KEY_A] >= 1){
				printf("asdf");
			}
		}
	}
	return NULL;


}

int main(void) 
{
	Config *cfg = init_config();
	read_config(cfg);

	DIR *events_entry = opendir("/dev/input");
	if (!events_entry) error("Devices","can not read devices directory.");
	int keys[KEY_MAX +1];

	int fd;
	char device[256],full_entry[50];

	while ((entry = readdir(events_entry))) {
		if (!is_keyboard(entry,&fd,full_entry,device)) continue;
		printf("%s\n",device);

		if (ioctl(fd,EVIOCGRAB,1) <0){
			error("grap", "");
		}

		int keys[KEY_MAX + 1]= {0};

		keyboard_loop();
		// while (read(fd, &ev, sizeof(ev))) {
		// 	if (ev.type == EV_KEY) {
		// 		keys[ev.code] = ev.value;
		// 		if (keys[KEY_SPACE] >= 1 && keys[KEY_A] >= 1){
		// 			printf("asdf");
		// 		}
		// 	}
		// }
	}

	free_cfg(cfg);
	sleep(5);
	closedir(events_entry);
	return 0;
}

