#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys\types.h>
#include <sys\stat.h>
#include <dos.h>
#include "dflat.h"

extern MENU MainMenu[];
extern DBOX FileOpen;

static char Untitled[] = "Untitled";
static int wndpos = 0;
static int DocumentCount = 0;

static int MemoPadProc(WINDOW, MESSAGE, PARAM, PARAM);
static void NewFile(WINDOW);
static void SelectFile(WINDOW);
static void OpenPadWindow(WINDOW, char *);
static void LoadFile(WINDOW, int);
static void PrintPad(WINDOW);
static void SaveFile(WINDOW, int);
static int EditorProc(WINDOW, MESSAGE, PARAM, PARAM);
static char *NameComponent(char *);

void main(int argc, char *argv[])
{
	int x,y;
	WINDOW wnd;
	init_messages();
	SendMessage(NULLWND, CURRENT_KEYBOARD_CURSOR, (PARAM)&x, (PARAM)&y);
	SendMessage(NULLWND, HIDE_CURSOR, 0, 0);

	wnd = CreateWindow(APPLICATION,
						"D-Flat MemoPad " VERSION,
						0, 0, SCREENHEIGHT, SCREENWIDTH,
						MainMenu,
						NULL,
						MemoPadProc,
						MOVEABLE | SIZEABLE);

	SendMessage(wnd, SETFOCUS, TRUE, 0);

	DeactivateCommand(ID_SAVE);
	DeactivateCommand(ID_SAVEAS);
	DeactivateCommand(ID_PRINT);

	while (argc > 1)	{
		OpenPadWindow(wnd, argv[1]);
		--argc;
		argv++;
	}

	while (dispatch_message())
		;

	SendMessage(NULLWND, KEYBOARD_CURSOR, x, y);
	SendMessage(NULLWND, SHOW_CURSOR, 0, 0);
}

static int MemoPadProc(WINDOW wnd, MESSAGE msg, PARAM p1, PARAM p2)
{
	switch (msg)	{
		case COMMAND:
			switch ((int)p1)	{
                case ID_NEW:
                    NewFile(wnd);
                    break;
                case ID_OPEN:
                    SelectFile(wnd);
                    break;
                case ID_SAVE:
                    SaveFile(inFocus, FALSE);
					break;
                case ID_SAVEAS:
                    SaveFile(inFocus, TRUE);
                    break;
                case ID_PRINT:
                    PrintPad(inFocus);
                    break;
				case ID_ABOUT:
					MessageBox(
						"About D-Flat and the MemoPad",
						"D-Flat is an operating environment\n"
						"that implements the SAA/CUA user\n"
						"interface in a C language library.\n"
						"    ------------------------ \n"
						"The MemoPad is a multiple document\n"
						"text editor that demonstrates the\n"
						"use of D-Flat.");
					break;
				default:
					break;
			}
			break;
		case CLOSE_WINDOW:	{
			WINDOW wnd1 = GetLastChild(wnd);
			while (wnd1 != NULLWND)	{
				if (GetClass(wnd1) == EDITBOX)
					SendMessage(wnd1, msg, p1, p2);
				wnd1 = GetPrevChild(wnd);
			}
			break;
		}
		default:
			break;
	}
	return DefaultWndProc(wnd, msg, p1, p2);
}

/*
 *  The New command. Open an empty editor window
 */
static void NewFile(WINDOW wnd)
{
    OpenPadWindow(wnd, Untitled);
}

/*
 *  The Open... command. Select a file 
 */
static void SelectFile(WINDOW wnd)
{
    char FileName[64];
    if (DlgOpenFile("*.PAD", FileName))	{
		/* --- see if the document is already in a window --- */
		WINDOW wnd1 = GetFirstChild(wnd);
		while (wnd1 != NULLWND)	{
			if (stricmp(FileName, wnd1->extension) == 0)	{
				SendMessage(wnd1, SETFOCUS, TRUE, 0);
				SendMessage(wnd1, RESTORE, 0, 0);
				return;
			}
			wnd1 = GetNextChild(wnd);
		}
        OpenPadWindow(wnd, FileName);
	}
}

/*
 *  open a document window and load a file
 */
static void OpenPadWindow(WINDOW wnd, char *FileName)
{
    WINDOW wnd1;
    struct stat sb;
	char *Fname = FileName;

    if (strcmp(FileName, Untitled))	{
		if (stat(FileName, &sb))    {
	        ErrorMessage("No such file");
    	    return;
	    }
		Fname = NameComponent(FileName);
	}

	wndpos += 2;
	if (wndpos == 20)
		wndpos = 2;

	wnd1 = CreateWindow(EDITBOX, Fname,
				(wndpos-1)*2, wndpos, 10, 40,
				NULL, wnd, EditorProc,
				MULTILINE |
				SHADOW |
				VSCROLLBAR |
				HSCROLLBAR |
				MINMAXBOX |
				CONTROLBOX |
				MOVEABLE |
				HASBORDER |
				SIZEABLE
	);

    if (strcmp(FileName, Untitled))	{
		if ((wnd1->extension = malloc(strlen(FileName)+1)) != NULL)	{
			strcpy(wnd1->extension, FileName);
    	    LoadFile(wnd1, (int) sb.st_size);
		}
	}
	SendMessage(wnd1, SETFOCUS, TRUE, 0);
}

/*
 *  Load the notepad file into the editor text buffer
 */
static void LoadFile(WINDOW wnd, int tLen)
{
    char *Buf;
    FILE *fp;

    if ((Buf = malloc(tLen+1)) != NULL)    {
        if ((fp = fopen(wnd->extension, "rt")) != NULL)    {
            memset (Buf, 0, tLen+1);
            fread(Buf, tLen, 1, fp);
		    SendMessage(wnd, SETTEXT, (PARAM) Buf, 0);
            fclose(fp);
        }
    }
}

/*
 *  print the current notepad
 */
static void PrintPad(WINDOW wnd)
{
	char *text;

	/* ---------- print the file name ---------- */
	fputs("\r\n", stdprn);
	fputs(GetTitle(wnd), stdprn);
	fputs(":\r\n\n", stdprn);

	/* ---- get the address of the editor text ----- */
	text = GetText(wnd);

	/* ------- print the notepad text --------- */
	while (*text)	{
		if (*text == '\n')
			fputc('\r', stdprn);
		fputc(*text++, stdprn);
	}

	/* ------- follow with a form feed? --------- */
	if (YesNoBox("Form Feed?"))
		fputc('\f', stdprn);
}

static void SaveFile(WINDOW wnd, int Saveas)
{
	FILE *fp;
	if (wnd->extension == NULL || Saveas)	{
		char FileName[64];
		if (DlgSaveAs(FileName))	{
			if (wnd->extension != NULL)
				free(wnd->extension);
			if ((wnd->extension = malloc(strlen(FileName)+1)) != NULL)	{
				strcpy(wnd->extension, FileName);
				AddTitle(wnd, NameComponent(FileName));
				SendMessage(wnd, BORDER, 0, 0);
			}
		}
	}
	if (wnd->extension != NULL)	{
		if ((fp = fopen(wnd->extension, "wt")) != NULL)	{
			fwrite(GetText(wnd), strlen(GetText(wnd)), 1, fp);
			fclose(fp);
			wnd->TextChanged = FALSE;
		}
	}
}

static int EditorProc(WINDOW wnd, MESSAGE msg, PARAM p1, PARAM p2)
{
	switch (msg)	{
		case CREATE_WINDOW:
			if (DocumentCount == 0)	{
				ActivateCommand(ID_SAVE);
				ActivateCommand(ID_SAVEAS);
				ActivateCommand(ID_PRINT);
			}
			DocumentCount++;
			break;
		case CLOSE_WINDOW:
			if (wnd->TextChanged)
				if (YesNoBox("Text changed. Save it?"))
					SendMessage(GetParent(wnd), COMMAND, ID_SAVE, 0);
			if (--DocumentCount == 0)	{
				DeactivateCommand(ID_SAVE);
				DeactivateCommand(ID_SAVEAS);
				DeactivateCommand(ID_PRINT);
			}
			wndpos = 0;
			if (wnd->extension != NULL)	{
				free(wnd->extension);
				wnd->extension = NULL;
			}
			break;
		default:
			break;
	}
	return DefaultWndProc(wnd, msg, p1, p2);
}

static char *NameComponent(char *FileName)
{
	char *Fname;
	if ((Fname = strrchr(FileName, '\\')) == NULL)
		if ((Fname = strrchr(FileName, ':')) == NULL)
			Fname = FileName-1;
	return Fname + 1;
}

