#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>

#include "globals.h"
#include "maildir.h"

int count_dir( const char * dirname ) {
	DIR * d = NULL;
	struct dirent * f = NULL;
	int ctotal = 0;

	if ( (d = opendir(dirname)) == NULL ) {
		return(-1);
	}

	while ( f = readdir(d) ) {
		if ( f->d_name[0] != '.' )
			++ctotal;
	}

	closedir(d);

	return(ctotal);
}

void maildir_handle( struct mbox_struct * mb ) {
	/* Since we never really intend to quit this function,
	 * all "global" stuff may go on the stack here */
	char dir_cur[MAX_INPUT_LENGTH];
	char dir_new[MAX_INPUT_LENGTH];
	int result;

	if ( ! strlen(mb->file) ) {
		printf("asmail: maildir_handle: no mailbox directory specified.\n");
		mb->status = STAT_FAIL;
		signal_update();
		pthread_exit(NULL);
	}
	printf("Handling the maildir %s every %d seconds.\n",
			mb->file, mb->update);
	strcpy(dir_cur, mb->file);
	strcat(dir_cur, "/cur");
	strcpy(dir_new, mb->file);
	strcat(dir_new, "/new");
	while (1) {
		mb->status = STAT_RUN;
		signal_update();
		result = count_dir(dir_cur);
		if ( result < 0 ) {
			mb->status = STAT_FAIL;
			signal_update();
		} else {
			if ( result )
				mb->mail = MAIL_OLD;
			else
				mb->mail = MAIL_NONE;
			mb->ctotal = result;
		}
		result = count_dir(dir_new);
		if ( result < 0 ) {
			mb->status = STAT_FAIL;
			signal_update();
		} else {
			if ( result ) {
				if ( mb->cnew != result ) {
					pthread_mutex_lock(&mb->mutex);
					mb->flags |= FLAG_ARRIVED;
					pthread_mutex_unlock(&mb->mutex);
				}
				mb->mail = MAIL_NEW;
			}
			mb->cnew = result;
			if ( mb->status == STAT_RUN ) 
				mb->status = STAT_IDLE;
		}
		signal_update();
		sleep_check(mb->update);
	}
}

