#include <windows.h>
#include "resource.h"
#include <atlstr.h>
#include <commctrl.h>
#include <iostream>
#include <fstream>
#include <iosfwd>
using namespace std;
 
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
char szFileName[256];
HWND hWnd;
HACCEL haccel;
HWND hb1;
HINSTANCE hInstance;
char szFile[260];
void FileOpen(HWND hWnd);
void setfont(HWND hWnd);
void FileSaveAs(HWND hwnd,char* filename);
HFONT hfFont;
long TextLength;
COLORREF crTextColor;
COLORREF crCustColors[16];
LOGFONT lfTemp={-16,0,0,0,400,0,0,0,DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,
                CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH,
                "Times New Roman"};

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{
	MSG msg;
    WNDCLASS wc;
    wc.style=CS_HREDRAW | CS_VREDRAW ;
    wc.lpfnWndProc=WndProc;
    wc.cbClsExtra=0;
    wc.cbWndExtra=0;
    wc.hInstance=hInstance;
    wc.hIcon=LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1));
    wc.hCursor=LoadCursor(hInstance, MAKEINTRESOURCE(IDC_CUR1));
    wc.hbrBackground=(HBRUSH)(6);
    wc.lpszMenuName=MAKEINTRESOURCE(IDR_MENU2);
    wc.lpszClassName="class";

	RegisterClass(&wc);

    hWnd=CreateWindow("class","SuperMegaTextEdit",WS_OVERLAPPEDWINDOW,150,100,500,400,0,0,hInstance,0);

	if (!hWnd)
    {
     MessageBox(NULL, "Error", "Error", MB_OK);
    }

    ShowWindow(hWnd, nCmdShow);

    UpdateWindow(hWnd);
    haccel = LoadAccelerators((HINSTANCE) hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1));
	while (GetMessage(&msg, NULL, 0, 0)) 
	{
    if(!TranslateAccelerator(hWnd,haccel,&msg))
        {
         TranslateMessage(&msg);
         DispatchMessage(&msg);
        }
    }
	return 0;
}


LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	int userReply;

	switch (message) 
	{
		case WM_CREATE:
			hb1=CreateWindow("Edit",NULL,
                            WS_CHILD|WS_VISIBLE|WS_HSCROLL|WS_VSCROLL|
                            WS_BORDER|ES_LEFT|ES_MULTILINE|ES_AUTOHSCROLL|
                            ES_AUTOVSCROLL,
                            0,0,0,0,
                            hWnd,0,hInstance,NULL);
                break;

		case WM_SETFOCUS:
            SetFocus(hb1);
                break;
          
        case WM_SIZE: 
            MoveWindow(hb1,0,0,LOWORD(lParam),HIWORD(lParam),TRUE);
                break;

		case WM_COMMAND:
		     wmId    = LOWORD(wParam);
		     wmEvent = HIWORD(wParam);
		switch (wmId)
		{
		case ID_FILE_LOAD:
			FileOpen(hWnd);
			break;
		case ID_FILE_SAVE40011:
			FileSaveAs(hWnd,szFileName);
			break;
		case ID_ABOUT_ABOUT:
			MessageBox(NULL, "Created by Dead MoroZZZ", "About", MB_OK|MB_ICONASTERISK);
			break;
		case ID_EDIT_UNDO40004:
			SendMessage(hb1,WM_UNDO,NULL,NULL);
			break;
		case ID_EDIT_CUT40007:
			SendMessage(hb1,WM_CUT,NULL,NULL);
			break;
		case ID_EDIT_COPY40008:
			SendMessage(hb1,WM_COPY,NULL,NULL);
			break;
		case ID_EDIT_PASTE40009:
			SendMessage(hb1,WM_PASTE,NULL,NULL);
			break;
		case ID_EDIT_DEL:
			SendMessage(hb1,WM_CLEAR,NULL,NULL);
			break;
		case ID_FORMAT_FONT40010:
			setfont(hb1);
			break;
		case ID_FILE_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;

		case WM_DESTROY:
			 PostQuitMessage(0);
			 break;

	    case WM_CLOSE: 
             userReply=MessageBox(NULL, "Are you shure?", "Exit", MB_YESNO|MB_ICONQUESTION);
             if(IDYES==userReply) 
             DestroyWindow(hWnd);
             break;
		default: 
			return DefWindowProc(hWnd, message, wParam, lParam); 
   }
return 0;
}

void setfont(HWND hWnd)
{
  static CHOOSEFONT cfTemp;

 cfTemp.lStructSize = sizeof( CHOOSEFONT );
 cfTemp.hwndOwner = hWnd;
 cfTemp.hDC = 0;
 cfTemp.lpLogFont = &lfTemp;
 cfTemp.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS|CF_INITTOLOGFONTSTRUCT|CF_EFFECTS;
 cfTemp.rgbColors = crTextColor;
 cfTemp.lCustData = 0L;
 cfTemp.lpfnHook = NULL;
 cfTemp.lpTemplateName = NULL;
 cfTemp.hInstance = 0;
 cfTemp.lpszStyle = NULL;
 cfTemp.nFontType = SCREEN_FONTTYPE;
 cfTemp.nSizeMin = 0;
 cfTemp.nSizeMax = 0;

  if( ChooseFont( &cfTemp ) == TRUE )
  {
   hfFont = CreateFontIndirect( &lfTemp ); //создание шрифта с выбранными параметрами
   SendMessage(hb1,WM_SETFONT,(WPARAM)hfFont,NULL);//установка шрифта в окне
   crTextColor=cfTemp.rgbColors;//установка цвета шрифта
  }
  InvalidateRect( hWnd, NULL, TRUE );
}

void FileSaveAs(HWND hwnd,char* filename)
{
  OPENFILENAME Save;
  FILE *fp;
  char szFiltr[] = "Текстовые файлы (*.txt)\0*.txt\0Все файлы (*.*)\0*.*\0";
      Save.lStructSize = sizeof( OPENFILENAME );
      Save.hwndOwner = hWnd;
      Save.hInstance = 0;
      Save.lpstrFilter = (LPSTR)szFiltr;
      Save.lpstrCustomFilter = NULL;
      Save.nMaxCustFilter = 0;
      Save.nFilterIndex = 1;
      Save.lpstrFile = (LPSTR)filename;  // имя файла
      Save.nMaxFile =256;
      Save.lpstrFileTitle = NULL;
      Save.nMaxFileTitle = 0;
      Save.lpstrInitialDir = NULL;
      Save.lpstrTitle = "Сохранить";  // Заголовок диалога
      Save.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST;
      Save.nFileOffset = 0;
      Save.nFileExtension = 0;
      Save.lpstrDefExt = "*";
      Save.lCustData = 0L;
      Save.lpfnHook = NULL;
      Save.lpTemplateName = NULL;

  if(GetSaveFileName(&Save)!=TRUE)
	  if(CommDlgExtendedError()==0)
		  return;

  InvalidateRect( hWnd, NULL, TRUE );
  fp=fopen(filename,"w");

  TextLength=SendMessage(hb1,WM_GETTEXTLENGTH,NULL,NULL)+1;
  char* bufer=new char[TextLength];
  SendMessage(hb1,WM_GETTEXT,TextLength,(LPARAM)bufer);
  fwrite(bufer, 1, strlen(bufer), fp);
  delete bufer;
  fclose(fp);
}



void FileOpen(HWND hWnd)
{
  OPENFILENAME ofn;
  HANDLE hf;    //дескриптор файла
  DWORD FileSize;  //размер файла
  //LPVOID Buffer;        //буфер для данных
  char title[10];

  ofn.lStructSize = sizeof( OPENFILENAME );
  ofn.hwndOwner = hWnd;
  ofn.hInstance = 0;
  ofn.lpstrFilter = "Текстовые файлы (*.txt)\0*.txt\0Все файлы (*.*)\0*.*\0";
  ofn.lpstrCustomFilter = NULL;
  ofn.nMaxCustFilter = 0;
  ofn.nFilterIndex = 1;
  ofn.lpstrFile = (LPSTR)szFileName;
  ofn.nMaxFile = sizeof( szFileName );
  ofn.lpstrFileTitle = title;
  ofn.nMaxFileTitle = 10;
  ofn.lpstrInitialDir = NULL;
  ofn.lpstrTitle = "Открыть";
  ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST;
  ofn.nFileOffset = 0;
  ofn.nFileExtension = 0;
  ofn.lpstrDefExt = "*";
  ofn.lCustData = 0L;
  ofn.lpfnHook = NULL;
  ofn.lpTemplateName = NULL;



  if(GetOpenFileName( &ofn ) == TRUE)
  {
   InvalidateRect( hWnd, NULL, TRUE );
   hf=CreateFile(szFileName,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,NULL,NULL);
  }
  else return;

  FileSize=GetFileSize(hf,NULL);
  char* Buffer=new char[FileSize];

  if(ReadFile(hf,Buffer,FileSize,&FileSize,NULL)==0)
           {
		    MessageBox(hWnd,"Ошибка при чтении файла!","Ошибка",MB_OK|MB_ICONSTOP);
            return;
		   }
  SendMessage(hb1,WM_SETTEXT,(WPARAM)0,(LPARAM)Buffer);

  SendMessage(hWnd,WM_SETTEXT,(WPARAM)0,(LPARAM)title);

  CloseHandle(hf);
  //TextLength=FileSize;
  delete Buffer;
}