
#Include Once "windows.bi"
#include once "win/richedit.bi"
#include once "win/commctrl.bi"
#Include Once "win/shellapi.bi"

#Include Once "inc/filestream.bi"
#Include Once "inc/xml.bi"
#Include Once "inc/http.bi"

#Include Once "fbedit/raedit.bi"
#Include Once "fbedit/addins.bi"

#Include Once "textformatplugin.bi"


'#Include Once "debug.bi"

Function TT(ByRef msg As String, ByRef tMsg As String = "") As String
	Dim tmpMsg As String = ""
	If tMsg <> "" Then tmpMsg = lpFunctions->FindString(lpData->hLangMem, "TextFormat", tMsg)
	If tmpMsg = "" Then tmpMsg = msg
	tmpMsg = ReplaceAll(tmpMsg, "%nl%", !"\n")
	tmpMsg = ReplaceAll(tmpMsg, "%tab%", !"\t")
	Return tmpMsg
End Function

Function TMsgBox(ByVal hWin As HWND, ByRef msg As String, ByRef tMsg As String = "", ByRef title As String = "", ByRef tTitle As String = "", ByVal param As Integer = 0) As Integer
	Dim tmpTitle As String = ""
	Dim tmpMsg As String = ""
	If tTitle <> "" Then tmpTitle = lpFunctions->FindString(lpData->hLangMem, "TextFormat", tTitle)
	If tmpTitle = "" Then tmpTitle = title
	If tmpTitle = "" Then
		tmpTitle = TT("TextFormat plugin", "textformat_plugin")
	Else
		tmpTitle = TT("TextFormat plugin", "textformat_plugin") + " - " + tmpTitle
	EndIf
	If tMsg <> "" Then tmpMsg = lpFunctions->FindString(lpData->hLangMem, "TextFormat", tMsg)
	If tmpMsg = "" Then tmpMsg = msg
	Return MessageBox(hWin, StrPtr(tmpMsg), StrPtr(tmpTitle), param)
End Function

'param = 1 - Alle MessageBoxes anzeigen; param = 0 - Nur Update-Meldung
Sub UpdateThread(param As Any Ptr)
	
	Dim Daten As XML
	Dim xmlnode As XML Ptr
	Dim xmlnode2 As XML Ptr
	Dim tmpStr As String
	Dim tmpStr2 As String
	
	If getHTTP(prgUpdateUrl, tmpStr) <> "" Then
		If param = 1 Then tMsgBox(lpHandles->hwnd, "Error while establishing connection to update-server", "err_upd_con", "Error", "error", MB_OK Or MB_ICONERROR)
		Exit Sub
	End If
	If Daten.Parse(tmpStr) <> 0 Then
		If param = 1 Then TMsgBox(0, "Error while parsing update-data (Invalid XML data)", "err_upd_xml", "Error", "error", MB_OK Or MB_ICONERROR)
		Exit Sub
	End If
	xmlnode = Daten.GetSubTag("version")
	If xmlnode = 0 Then
		If param = 1 Then TMsgBox(0, "Error while parsing update-data (Version number not found)", "err_upd_ver", "Error", "error", MB_OK Or MB_ICONERROR)
		Exit Sub
	End If
	xmlnode2 = Daten.GetSubTag("url")
	If prgVersion <> xmlnode->Daten Then
		If xmlnode2 = 0 Then
			tmpStr = TT("An update is available for your version of the TextFormat plugin.", "upd_msg1") + CRLF + CRLF + TT("Your current version is: ", "upd_curver") + prgVersion + CRLF + TT("The latest version is: ", "upd_newver") + xmlnode->Daten + CRLF + CRLF + TT("Please keep your plugin up to date to ensure reliability in future", "upd_msg2")
			tmpStr2 = TT("TextFormat plugin", "textformat_plugin") + " - " + TT("Update available", "upd_avail")
			MessageBox(lpHandles->hwnd, StrPtr(tmpStr), StrPtr(tmpStr2), MB_OK Or MB_ICONINFORMATION)
		Else
			tmpStr = TT("An update is available for your version of the TextFormat plugin.", "upd_msg1") + CRLF + CRLF + TT("Your current version is: ", "upd_curver") + prgVersion + CRLF + TT("The latest version is: ", "upd_newver") + xmlnode->Daten + CRLF + CRLF + TT("Please keep your plugin up to date to ensure reliability in future", "upd_msg2") + CRLF + CRLF + TT("Do you want to open the homepage now to download the latest version?", "upd_now")
			tmpStr2 = TT("TextFormat plugin", "textformat_plugin") + " - " + TT("Update available", "upd_avail")
			If MessageBox(lpHandles->hwnd,  StrPtr(tmpStr), StrPtr(tmpStr2), MB_YESNO Or MB_ICONQUESTION) = IDYES Then _
				ShellExecute(lpHandles->hwnd, @"open" , StrPtr(xmlnode2->Daten) , NULL, NULL, SW_SHOWNORMAL)
		End If
	Else
		If param = 1 Then tMsgBox(lpHandles->hwnd, "Your version of the TextFormat plugin is up to date", "upd_uptodate",,, MB_OK Or MB_ICONINFORMATION)
	End If
	
	tUpdate = 0
	
End Sub


Function askConvert(fileName As String) As Integer
	If Sett.autoconv <> 0 Then Return TRUE
	Dim tmpMsg As String
	Dim tmpTitle As String
	tmpMsg = TT("The file given below contains line endings that differ from standard Windows line breaks:", "cvMsg1") + CRLF + fileName + CRLF + CRLF + TT("The line endings have to be converted so that the file can be displayed correctly by FBEdit.", "cvMsg2") + CRLF + TT("Would You like to convert the file now?", "cvMsg3")
	tmpTitle = TT("TextFormat plugin", "textformat_plugin") + " - " + TT("incompatible line endings", "endofline_wrong")
	return MessageBox(lpHandles->hwnd, StrPtr(tmpMsg), StrPtr(tmpTitle), MB_YESNOCANCEL Or MB_ICONQUESTION)
End Function



Function InstallDll CDECL alias "InstallDll" (byval hWin as HWND,byval hInst as HINSTANCE) as ADDINHOOKS ptr EXPORT

	lpHandles = Cast(ADDINHANDLES ptr, SendMessage(hWin, AIM_GETHANDLES, 0, 0))
	lpData = Cast(ADDINDATA ptr, SendMessage(hWin, AIM_GETDATA, 0, 0))
	lpFunctions = Cast(ADDINFUNCTIONS ptr, SendMessage(hWin,AIM_GETFUNCTIONS, 0, 0))
	
	lpFunctions->LoadFromIni("TextFormat", "Settings", "44", @Sett, FALSE)
	
	netStart()
	If Sett.updates <> 0 Then If tUpdate = 0 Then tUpdate = ThreadCreate(@UpdateThread)
	
	hooks.hook1 = HOOK_FILEOPEN or HOOK_CLOSE
	hooks.hook2 = 0
	hooks.hook3 = 0
	hooks.hook4 = 0
	return @hooks

End Function

Function DllFunction CDECL alias "DllFunction" (byval hWin as HWND,byval uMsg as UINT,byval wParam as WPARAM,byval lParam as LPARAM) as bool EXPORT
	
	Select Case uMsg
						
		Case AIM_CLOSE
			netStop()
			lpFunctions->SaveToIni("TextFormat", "Settings", "44", @Sett, FALSE)
			
			
		Case AIM_FILEOPEN
			Dim fileName As String
			Dim fileData As String
			Dim fileDatC As UByte
			Dim fileEnc As String
			Dim expectLF As Integer = FALSE
			Dim convTF As Integer = FALSE
			fileName = *Cast(ZString Ptr, lParam)
			
			Dim fs As FileStream Ptr
			fs = New FileStream(fileName)
			
			While Not fs->atEOF
				
				fileDatC = fs->ReadByte()
				
				If fileDatC = CR Then
					If expectLF = TRUE Then
						If convTF = FALSE Then
							Select Case askConvert(fileName)
								Case IDYES:
									convTF = TRUE
								Case IDNO:
									Delete fs
									Return FALSE
								Case Else:
									Delete fs
									Return TRUE
							End Select
						EndIf
						fileData += CRLF
					EndIf
					expectLF = TRUE
				ElseIf fileDatC = LF Then
					If expectLF = FALSE AndAlso convTF = FALSE Then
						Select Case askConvert(fileName)
							Case IDYES:
								convTF = TRUE
							Case IDNO:
								Delete fs
								Return FALSE
							Case Else:
								Delete fs
								Return TRUE
						End Select
					EndIf
					fileData += CRLF
					expectLF = FALSE
				Else
					If expectLF Then
						If convTF = FALSE Then
							Select Case askConvert(fileName)
								Case IDYES:
									convTF = TRUE
								Case IDNO:
									Delete fs
									Return FALSE
								Case Else:
									Delete fs
									Return TRUE
							End Select
						EndIf
						fileData += CRLF
						expectLF = FALSE
					EndIf
					fileData += Chr(fileDatC)
				EndIf
				
				If fileEnc = "" Then
					If Len(fileData) = 2 Then
						If fileData = Chr(&HFF, &HFE) Then
							fileEnc = "UCS-2 (LE)"
						ElseIf fileData = Chr(&HFE, &HFF) Then
							fileEnc = "UCS-2 (BE)"
						EndIf
					ElseIf Len(fileData) = 3 Then
						If fileData = Chr(&HEF, &HBB , &HBF) Then
							fileEnc = "UTF-8"
						EndIf
					ElseIf Len(fileData) = 4 Then
						If fileData = Chr(&HFF, &HFE, 0, 0) Then
							fileEnc = "UCS-4 (LE)"
						ElseIf fileData = Chr(0, 0, &HFE, &HFF) Then
							fileEnc = "UCS-4 (BE)"
						EndIf
					EndIf
					If fileEnc <> "" Then
						Dim tmpMsg As String
						Dim tmpTitle As String
						tmpMsg = ReplaceAll(TT("The file seems to be %enc% encoded." + CRLF + "This encoding isn't supported by FBEdit." + CRLF + CRLF + "Do You want to try to open the file anyway?", "msgEnc"), "%enc%", fileEnc)
						tmpTitle = TT("TextFormat plugin", "textformat_plugin") + " - " + TT("warning", "warning")
						If MessageBox(lpHandles->hwnd, StrPtr(tmpMsg), StrPtr(tmpTitle), MB_YESNO Or MB_ICONWARNING) <> IDYES Then
							Delete fs
							Return TRUE
						Else
							Delete fs
							Return FALSE
						EndIf
					EndIf
				EndIf
				
			Wend
			If expectLF = TRUE Then
				If convTF = FALSE Then
					convTF = askConvert(fileName)
					If convTF = FALSE Then
						Delete fs
						Return TRUE
					EndIf
				EndIf
				fileData += CRLF
			EndIf
			
			'fs->CloseStream()
			Delete fs
			
			If convTF Then
				Dim FF As Integer = FreeFile()
				If Open(fileName, For Binary, as #FF) = 0 Then
					Put #FF,1,fileData
					Close #FF
				Else
					TMsgBox(lpHandles->hwnd, "The file couldn't be updated.", "err_nowrite", "error", "error", MB_OK Or MB_ICONERROR)
					Return TRUE
				EndIf
			EndIf
			
	end select
	return FALSE
End Function
