/*
README:

There is an assumption that all folders that are being
subscribed to are in Cached in the database.  This starts
out this way by reading in the subscription information
when the database is created and its attributes set.

Also assumes that we need to read in the folder list
only once.

TODO: Add explicit research list of folders.  This will
probably be part of an entire section of stuff that 
rescans lots of information
*/


#include <andrewos.h>
#include <class.h>
#include <stdlib.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <pwd.h>
#include <errno.h>
#include <util.h>

#include <directory.ih>
#include <extlist.ih>
#include <fldlist.ih>
#include <attrvalst.ih>
#include <environ.ih>
#include <amsconf.ih>
#include <mhmlbox.ih>
#include <msgfolder.ih>
#include <mhfolder.ih>
#include <mhdb.eh>

#define BUFFSIZE 1000

static char *defaultMailBox;
static char *defaultMailPath;
static struct directory *statusDirectory;
static long defaultFolderProtection;

static boolean SetDefaultMailDirectory(mhProfile)
struct configurelist *mhProfile;
{
    char *ptr = environ_GetConfig(mhProfile, "Path", TRUE);
    char str[MAXPATHLEN];

    if (ptr == NULL || *ptr == '\0') {
	ptr = "Mail";
    }
    if (*ptr != '/') {
	sprintf(str, "%s/%s", environ_GetHome(NULL), ptr);
	ptr = str;
    }
    defaultMailPath = (char *) malloc(strlen(ptr) + 1);
    strcpy(defaultMailPath, ptr);

    return FALSE;
}

static boolean SetDefaultMailbox(mhProfile)
struct configurelist *mhProfile;
{
    char *ptr;
    char str[MAXPATHLEN];

#ifdef AMS_DELIVERY_ENV
    {
	sprintf(str, "%s/Mailbox", environ_GetHome(NULL));
    }
#else /* ! AMS_DELIVERY_ENV */
    {
	struct passwd *ent;

	ent = getvpwuid(getvuid());
	if (ent != NULL) {
	    sprintf(str, "%s/%s", amsconfiguration_GetString("AMS_MailBoxPrefix"), ent->pw_name);
	}
	else {
	    str[0] = '\0';
	}
    }
#endif /* AMS_DELIVERY_ENV */
    defaultMailBox = (char *) malloc(strlen(str) + 1);
    strcpy(defaultMailBox, str);

    return FALSE;
}

static boolean SetDefaultFolderProtection(mhProfile)
struct configurelist *mhProfile;
{
    char *ptr;
    
    ptr = environ_GetConfig(mhProfile, "Folder-Protect", TRUE);
    if (ptr == NULL || *ptr == '\0') {
	defaultFolderProtection = 0711;
    }
    else {
	defaultFolderProtection = strtol(ptr, NULL, 8);
    }

    return FALSE;
}

static boolean SetStatusDirectory()
{
    char *ptr;
    char str[MAXPATHLEN];
    struct stat stbuf;

    ptr = environ_GetProfile("AMSMHStatusDirectory");
    if (ptr == NULL || *ptr == '\0') {
	ptr = ".MH";
    }
    if (*ptr != '/') {
	sprintf(str, "%s/%s", environ_GetHome(NULL), ptr);
	ptr = str;
    }

    statusDirectory = directory_Get(ptr);
    if (statusDirectory == NULL) {
	statusDirectory = directory_Create(ptr, 0711);
	if (statusDirectory == NULL) {
		/* TODO: Error in dealing with directory */
	}
    }
    /* TODO: Verify that you can read and write in this directory */
    return FALSE;
}

boolean mhdatabase__InitializeClass(classid)
struct classheader *classid;
{
    char str[MAXPATHLEN];
    char *ptr;
    struct configurelist *mhProfile;
    boolean error;

    sprintf(str, "%s/.mh_profile", environ_GetHome(NULL));

    mhProfile = environ_ReadConfigureFile(str);

    error = SetDefaultMailDirectory(mhProfile);
    if (! error) {
	error = SetDefaultMailbox(mhProfile);
	if (! error) {
	    error = SetDefaultFolderProtection(mhProfile);
	}
    }


    environ_FreeConfigureList(mhProfile);

    if (! error) {
	error = SetStatusDirectory();
    }

    return ! error;
}

static void DestroyMailboxes(mailbox)
struct mhmailbox *mailbox;
{
    mhmailbox_Destroy(mailbox);
}

boolean mhdatabase__InitializeObject(classid, self)
struct classheader *classid;
struct mhdatabase *self;
{
    self->profileFileName = NULL;
    self->folderPriority = 0;
    self->mailboxes = extendedlist_Create(NULL, DestroyMailboxes);
    self->scannedInAllFolders = FALSE;

    return TRUE;
}

void mhdatabase__FinalizeObject(classid, self)
struct classheader *classid;
struct mhdatabase *self;
{
    extendedlist_Destroy(self->mailboxes);
}


static void ProcessMailboxInfo(self, attrValList, useDefaultMailBox)
struct mhdatabase *self;
struct attributevalueset *attrValList;
boolean useDefaultMailBox;
{
    char *mailpath = NULL;
    char *mailboxtype;
    char *mailboxfolder;
    struct stat stbuf;
    char mbf[MAXPATHLEN];
    char mailboxclass[MAXPATHLEN];
    struct mhmailbox *mailbox;
    struct msgfolder *folder;

    if (attributevalueset_Lookup(attrValList, "mailbox", &mailpath) || useDefaultMailBox) {
	if (mailpath == NULL) {
	    mailpath = defaultMailBox;
	}

	if (! attributevalueset_Lookup(attrValList, "mailboxtype", &mailboxtype)) {
	    if (stat(mailpath, &stbuf) != 0) {
		mailboxtype = "unix";
	    }
	    else if ((stbuf.st_mode & S_IFMT) == S_IFDIR) {
		mailboxtype = "ams";
	    }
	    else {
		mailboxtype = "unix";
	    }
	}

	if (! attributevalueset_Lookup(attrValList, "mailfolder", &mailboxfolder)) {
	    mailboxfolder = "inbox";
	}

	folder = mhdatabase_GetFolder(self, mailboxfolder);
	if (folder != NULL && msgfolder_IsPersonal(folder)) {

	    sprintf(mailboxclass, "%smhmailbox", mailboxtype);
	    mailbox = (struct mhmailbox *) class_NewObject(mailboxclass);

	    if (mailbox != NULL) {
		mhmailbox_SetDatabase(mailbox, self);
		mhmailbox_SetFolderName(mailbox, mailboxfolder);
		mhmailbox_SetSource(mailbox, mailpath);
		extendedlist_AddElement(self->mailboxes, mailbox);
	    }
	}
    }
}

static void ProcessMailList(self, mailList)
struct mhdatabase *self;
char *mailList;
{
    struct fieldlist *info;

    info = fieldlist_Create(mailList, ":", '{', '}', NULL);
    if (info != NULL) {
	long count = fieldlist_NumberOfElements(info);
	long i;

	for (i = 0; i < count; i++) {
	    char *entry = fieldlist_GetNth(info, i);
	    struct attributevalueset *mailAttr;

	    mailAttr = attributevalueset_New();
	    if (mailAttr != NULL) {
		attributevalueset_ParseString(mailAttr, entry, '\0', '\0');
		ProcessMailboxInfo(self, mailAttr, FALSE);
		attributevalueset_Destroy(mailAttr);
	    }
	}

	fieldlist_Destroy(info);
    }
}

static void SetProfileFileName(self, attrValList, useDefault)
struct mhdatabase *self;
struct attributevalueset *attrValList;
boolean useDefault;
{
    char *ptr = NULL;
    char str[MAXPATHLEN];

    if (! attributevalueset_Lookup(attrValList, "profile", &ptr) && useDefault) {
	ptr = "profile";
    }
   
    if (ptr != NULL) {
	if (*ptr != '/') {
	    self->profileFileName = directory_GetFullFileName(statusDirectory, ptr, NULL);
	}
	else {
	    self->profileFileName = (char *) malloc(strlen(ptr) + 1);
	    strcpy(self->profileFileName, ptr);
	}
    }
}

static boolean ProcessProfileFile(self, profileFile)
struct mhdatabase *self;
FILE *profileFile;
{
    char buffer[MAXPATHLEN + 100];
    char *folderName;
    struct mhfolder *folder;
    char *subscriptionInfoStr;
    enum msgsubscription subscriptionInfo;
    char *lastFileNumberStr;
    long lastFileNumber;
    char *receiveTimeStampStr;
    long receiveTimeStamp;
    struct fieldlist *fl = fieldlist_New();

    while (fgets(buffer, sizeof(buffer), profileFile)) {
	fieldlist_Parse(fl, buffer, " \t", '\0', '\0');

	folderName = fieldlist_GetNth(fl, 0);

	if (*folderName != NULL) {
	    subscriptionInfoStr = fieldlist_GetNth(fl, 1);
	    lastFileNumberStr = fieldlist_GetNth(fl, 2);
	    receiveTimeStampStr = fieldlist_GetNth(fl, 3);

	    if (subscriptionInfoStr == NULL) {
		subscriptionInfo = msgsubscription_None;
	    }
	    else {
		switch (*subscriptionInfoStr) {
		    case 's':
		    case 'S':
			subscriptionInfo = msgsubscription_Normal;
			break;
		    case 'n':
		    case'N':
			subscriptionInfo = msgsubscription_No;
			break;
		    default:
			subscriptionInfo = msgsubscription_None;
			break;
		}

	    }

	    lastFileNumber = (lastFileNumberStr == NULL) ? 0 : atoi(lastFileNumberStr);
	    receiveTimeStamp = (receiveTimeStampStr == NULL) ? 0 : atoi(receiveTimeStampStr);

	    /*
	     TODO: There is a problem with this in that if
		 a folder does not exist or cant be found
		 becuase of file system problems, then the
		 entry will be removed from the subscription
		 list.  Need a better solution than that
		 */

	    folder = (struct mhfolder *) mhdatabase_GetFolder(self, folderName);
	    if (folder != NULL) {
		long prevNumber = mhfolder_GetLastMessageFileNumber(folder);
		long prevReceiveTime = mhfolder_GetReceiveTimeStamp(folder);

		if (lastFileNumber > prevNumber) {
		    mhfolder_SetLastMessageFileNumber(folder, lastFileNumber);
		}
		if (receiveTimeStamp > prevReceiveTime) {
		    mhfolder_SetReceiveTimeStamp(folder, receiveTimeStamp);
		}
		if (mhfolder_GetSubscription(folder) == msgsubscription_None) {
		    mhfolder_SetSubscription(folder, subscriptionInfo);
		}
		mhfolder_SetOrderPriority(folder, self->folderPriority);
		self->folderPriority++;
	    }
	}
	fieldlist_Clear(fl);
    }

    fieldlist_Destroy(fl);

    return FALSE;
}
    
struct addallfoldersinfo {
    struct mhdatabase *self;
    long subscription;
};

static boolean AddFolderToProfile(folderName, info)
char *folderName;
struct addallfoldersinfo *info;
{
    struct msgfolder *folder = mhdatabase_GetFolder(info->self, folderName);

    if (folder != NULL) {
	struct extendedlist *folderList = msgfolder_GetListOfSubFolders(folder);

	if (msgfolder_GetSubscription(folder) == msgsubscription_None) {
	    msgfolder_SetSubscription(folder, info->subscription);
	}
	
	if (msgfolder_GetOrderPriority(folder) == -1) {
	    msgfolder_SetOrderPriority(folder, info->self->folderPriority);
	    info->self->folderPriority++;
	}

	extendedlist_ForEach(folderList, AddFolderToProfile, info); 
	extendedlist_Destroy(folderList);
    }
    return FALSE;
}


static int FolderNameCompare(name1, name2)
char *name1;
char *name2;
{
    int cmp;

    if ((cmp = strcmp(name1, name2)) == 0) {
	return 0;
    }
    if (strcmp(name1, "inbox") == 0) {
	return -1;
    }
    if (strcmp(name2, "inbox") == 0) {
	return 1;
    }
    return cmp;
}

static boolean AddAllFoldersWork(name, info)
char *name;
struct addallfoldersinfo *info;
{
    struct msgfolder *folder;

    if (index(name, '.') == NULL) {
	AddFolderToProfile(name, info);
    }
    return FALSE;
}

static boolean AddAllFolders(self, subscription)
struct mhdatabase *self;
enum msgsubscription subscription;
{
    struct directory *dir;
    char *path = mhdatabase_GetPath(self);
    struct addallfoldersinfo info;

    dir = directory_Get(path);
    if (dir != NULL) {
	struct extendedlist *list = directory_GetSubDirectoryList(dir);
	info.self = self;
	info.subscription = subscription;
	extendedlist_ForEach(list, AddAllFoldersWork, &info);
	extendedlist_Destroy(list);
	directory_Destroy(dir);
    }

    return FALSE;
}

static ConvertFolderNameToFullPath(self, folderName, folderPathName)
struct mhdatabase *self;
char *folderName;
char *folderPathName;
{
    char *path;
    char *p;
    char *q;

    if ((path = mhdatabase_GetPath(self)) != NULL) {
	strcpy(folderPathName, path);
	p = &folderPathName[strlen(folderPathName)];
	*p++ = '/';
    }
    else {
	folderPathName[0] = '\0';
	p = folderPathName;
    }

    for (q = folderName; *q != '\0'; q++) {
	if (*q == '.') {
	    *p++ = '/';
	}
	else {
	    *p++ = *q;
	}
    }
    *p = '\0';
}


void mhdatabase__SetAttributes(self, attrValList)
struct mhdatabase *self;
struct attributevalueset *attrValList;
{
    char str[MAXPATHLEN];
    char *path;
    char *mailList;
    boolean isDefaultPath = FALSE;

    super_SetAttributes(self, attrValList);

    path = mhdatabase_GetPath(self);

    if (path == NULL || *path == '\0') {
	path = defaultMailPath;
	isDefaultPath = TRUE;
    }
    else {
	if (*path != '/') {
	    sprintf(str, "%s/%s", environ_GetHome(NULL), path);
	    path = str;
	}
	isDefaultPath = (strcmp(path, defaultMailPath) == 0);
    }
	
    mhdatabase_SetPath(self, path);

    ProcessMailboxInfo(self, attrValList, isDefaultPath);
    SetProfileFileName(self, attrValList, isDefaultPath);
    mhdatabase_ReadProfile(self);

    if (attributevalueset_Lookup(attrValList, "mailboxlist", &mailList)) {
	ProcessMailList(self, mailList);
    }
}

static int StrCompare(str1, str2)
struct msgfolder **str1;
struct msgfolder **str2;
{
    return strcmp(msgfolder_GetName(*str1), msgfolder_GetName(*str2));
}

struct patterninfo {
    char *pattern;
    long len;
};

static boolean CheckPattern(folder, info)
struct msgfolder *folder;
struct patterninfo *info;
{
    return (strncmp(info->pattern, msgfolder_GetName(folder), info->len) == 0);
}

struct extendedlist *mhdatabase__GetListOfAllFolders(self, pattern, count)
struct mhdatabase *self;
char *pattern;
long *count;
{
    struct extendedlist *folderList;
    struct patterninfo info;

    if (! self->scannedInAllFolders) {
	AddAllFolders(self, msgsubscription_None);
	self->scannedInAllFolders = TRUE;
    }

    folderList = mhdatabase_GetCacheList(self);
    if (pattern != NULL) {
	info.pattern = pattern;
	info.len = strlen(pattern);
	extendedlist_Prune(folderList, CheckPattern, &info);
	extendedlist_Reduce(folderList);
    }
    extendedlist_Sort(folderList, StrCompare);
    return folderList;
}

static boolean CheckPatternAndSubscription(folder, info)
struct msgfolder *folder;
struct patterninfo *info;
{
    enum msgsubscription sub = msgfolder_GetSubscription(folder);

    return (sub != msgsubscription_No
	     && sub != msgsubscription_None
	     && strncmp(info->pattern, msgfolder_GetName(folder), info->len) == 0);
}

struct extendedlist *mhdatabase__GetListOfSubscribedFolders(self, pattern)
struct mhdatabase *self;
char *pattern;
{
    struct extendedlist *folderList;
    struct patterninfo info;

    folderList = mhdatabase_GetCacheList(self);
    if (pattern != NULL) {
	info.pattern = pattern;
	info.len = strlen(pattern);
	extendedlist_Prune(folderList, CheckPatternAndSubscription, &info);
	extendedlist_Reduce(folderList);
    }
    extendedlist_Sort(folderList, StrCompare);
    return folderList;
}

long mhdatabase__NumberOfMailBoxes(self)
struct mhdatabase *self;
{
    return (extendedlist_NumberOfElements(self->mailboxes));
}

struct msgmailbox *mhdatabase__GetMailBox(self, num)
struct mhdatabase *self;
long num;
{
    extendedlist_GetNth(self->mailboxes, num);
}

struct msgfolder *mhdatabase__GetFolder(self, folderName)
struct mhdatabase *self;
char *folderName;
{
    char folderPathName[MAXPATHLEN];
    struct mhfolder *folder;
    struct msgfolder *cachedFolder;
    
    cachedFolder = super_GetFolder(self, folderName);
    if (cachedFolder != NULL) {
	return cachedFolder;
    }

    ConvertFolderNameToFullPath(self, folderName, folderPathName);

    folder = mhfolder_Get(self, folderName, folderPathName);

    if (folder != NULL) {
	mhdatabase_CacheFolder(self, folder);
    }

    return (struct msgfolder *) folder;
}

struct msgfolder *mhdatabase__CreateFolder(self, folderName)
struct mhdatabase *self;
char *folderName;
{
    char folderPathName[MAXPATHLEN];
    struct mhfolder *folder;

    if (mhdatabase_GetFolder(self, folderName) != NULL) {
	return NULL;
    }

    ConvertFolderNameToFullPath(self, folderName, folderPathName);

    folder = mhfolder_CreateNewFolder(self, folderName, folderPathName, defaultFolderProtection);

    if (folder != NULL) {
	mhdatabase_CacheFolder(self, folder);
    }

    return (struct msgfolder *) folder;
}

static boolean CheckForNewMail(mailbox, rock)
struct mhmailbox *mailbox;
void *rock;
{
    return mhmailbox_IsThereNewMail(mailbox);
}

boolean mhdatabase__IsThereNewMail(self)
struct mhdatabase *self;
{
    return extendedlist_ForEach(self->mailboxes, CheckForNewMail, NULL) >= 0;
}

static boolean CountNewMail(mailbox, count)
struct mhmailbox *mailbox;
long *count;
{
    *count += mhmailbox_CountOfNewMail(mailbox);
    return FALSE;
}

long mhdatabase__CountOfNewMail(self)
struct mhdatabase *self;
{
    long count = 0;

    extendedlist_ForEach(self->mailboxes, CountNewMail, &count);
    return count;
}

struct processinfo {
    long good;
    long bad;
    long locked;
    long error;
    boolean errorFound;
    char *buffer;
    long bufferSize;
};

static boolean ProcessNewMail(mailbox, info)
struct mhmailbox *mailbox;
struct processinfo *info;
{
    long good;
    long bad;
    long locked;
    long error;
    char buffer[BUFFSIZE];

    if (mhmailbox_ProcessNewMail(mailbox, &good, &bad, &locked, &error, buffer, BUFFSIZE) != 0) {
	if (! info->errorFound) {
	    long copySize;

	    info->errorFound = TRUE;
	    info->error = error;
	    copySize = (BUFFSIZE > info->bufferSize) ? info->bufferSize : BUFFSIZE;
	    /* TODO: Boundary condition in strncpy */
	    strncpy(info->buffer, buffer, copySize);
	}
	info->good += good;
	info->bad += bad;
	info->locked += locked;
    }
    return FALSE;
}

boolean mhdatabase__ProcessNewMail(self, numGood, numBad, numLocked, firstError, errorBuf, bufferSize)
struct mhdatabase *self;
long *numGood;
long *numBad;
long *numLocked;
long *firstError;
char *errorBuf;
long bufferSize;
{
    struct processinfo info;
    
    info.good = 0;
    info.bad = 0;
    info.locked = 0;
    info.errorFound = FALSE;
    info.error = 0;
    info.buffer = errorBuf;
    info.bufferSize = bufferSize;

    extendedlist_ForEach(self->mailboxes, ProcessNewMail, &info);

    if (numGood != NULL) {
	*numGood = info.good;
    }
    if (numBad != NULL) {
	*numBad = info.bad;
    }
    if (numLocked != NULL) {
	*numLocked = info.locked;
    }
    if (firstError != NULL) {
	*firstError = info.error;
    }
    return info.errorFound;
}

boolean mhdatabase__ReadProfile(self)
struct mhdatabase *self;
{
    FILE *profileFile;
    boolean error = FALSE;


    if (self->profileFileName != NULL) {
	profileFile = fopen(self->profileFileName, "r");

	if (profileFile != NULL) {
	    error = ProcessProfileFile(self, profileFile);
	    fclose(profileFile);
	    return error;
	}
    }

    /*
      If we get here then there is no profile.  This
      can be a result of the profile file not existing
      there was no profile file specified.  The notion
      here is to generate the full file list and go on
      from there.  If we can not write it later that
      will be handled then.
      */

    return AddAllFolders(self, msgsubscription_Normal);
}

static int ComparePriority(folder1, folder2)
struct msgfolder **folder1;
struct msgfolder **folder2;
{
    long op1 = msgfolder_GetOrderPriority(*folder1);
    long op2 = msgfolder_GetOrderPriority(*folder2);

    if (op1 < op2) {
	return -1;
    }
    else if (op1 > op2) {
	return 1;
    }
    else {
	return strcmp(msgfolder_GetName(*folder1), msgfolder_GetName(*folder2));
    }
}

static boolean SaveFolderProfile(folder, file)
struct mhfolder *folder;
FILE *file;
{
    char subscription;
    enum msgsubscription sub = mhfolder_GetSubscription(folder);
    long lastFileNumber = mhfolder_GetLastMessageFileNumber(folder);

    if (sub != msgsubscription_None || lastFileNumber != 0) {

	switch (sub) {
	    case msgsubscription_No:
		subscription = 'n';
		break;
	    case msgsubscription_Normal:
		subscription = 's';
		break;
	    default:
		subscription = 'X';
		break;
	}

	fprintf(file, "%s\t%c\t%d\t%d\n", mhfolder_GetName(folder), subscription, lastFileNumber, mhfolder_GetReceiveTimeStamp(folder));
    }
    return FALSE;
}

boolean mhdatabase__SaveProfile(self)
struct mhdatabase *self;
{
    long entries = mhdatabase_NumberOfCachedFolders(self);
    char newFileName[MAXPATHLEN];
    char backupFileName[MAXPATHLEN];
    FILE *profileFile;
    long len;

    /* TODO: Need to handle locking of the file */
    /* TODO: Need better error handling when saving the profile */

    if (self->profileFileName == NULL) {
	return;
    }

    len = strlen(self->profileFileName);
    strcpy(newFileName, self->profileFileName);
    strcpy(backupFileName, self->profileFileName);
    strcpy(&newFileName[len], ".NEW");
    strcpy(&backupFileName[len], ".BAK");

    profileFile = fopen(newFileName, "w");
    if (profileFile != NULL) {
	struct extendedlist *folderList  = mhdatabase_GetCacheList(self);

	extendedlist_Sort(folderList, ComparePriority);

	extendedlist_ForEach(folderList, SaveFolderProfile, profileFile);

	fclose(profileFile);
	if (rename(self->profileFileName, backupFileName) == 0) {
	    if (rename(newFileName, self->profileFileName) == 0) {
		return FALSE;
	    }
	}
    }
    return TRUE;
}

boolean mhdatabase__CheckpointProfile(self)
struct mhdatabase *self;
{
    return TRUE;
}

