'
' Created by SharpDevelop.
' User: Jano
' Date: 22.7.2017
' Time: 18:16
' modul1 po testovanie v menu a aj s prihlasovanim
' To change this template use Tools | Options | Coding | Edit Standard Headers.
Imports System.Net
Imports System.IO
Imports System
Imports System.Security.Cryptography
Imports System.Text.RegularExpressions
Imports System.Text
Public Class Module1
	
	Function GetMd5Hash(ByVal md5Hash As MD5, ByVal input As String) As String 'pomocna funkcia pre md5

        ' Convert the input string to a byte array and compute the hash.
        Dim data As Byte() = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input))

        ' Create a new Stringbuilder to collect the bytes
        ' and create a string.
        Dim sBuilder As New StringBuilder()

        ' Loop through each byte of the hashed data 
        ' and format each one as a hexadecimal string.
        Dim i As Integer
        For i = 0 To data.Length - 1
            sBuilder.Append(data(i).ToString("x2"))
        Next i

        ' Return the hexadecimal string.
        Return sBuilder.ToString()

    End Function 'GetMd5Hash
    
    Public Function vratMD5(retazec As String) As String 'vyuziva pomocnu funkciu GetMd5Hash
    	Dim md5heslo As String
    	' Convert the input string to a byte array and compute the hash.
    	Using md5Hash As MD5 = MD5.Create()
    		md5heslo=GetMd5Hash(md5Hash,retazec)
		End Using
        ' Return the hexadecimal string.
        Return md5heslo
    End Function
    
	Public Function zapisNobody() 'pri starte programu si zapisem, ak treba nobodyho, alebo aj inde
		Try
		    Dim filePath As String
		    filePath = System.IO.Path.Combine(
		    My.Computer.FileSystem.SpecialDirectories.MyDocuments, "ktojeprihl.txt")
		    My.Computer.FileSystem.WriteAllText(filePath, "nobody", False)
		Catch fileException As Exception
		    Throw fileException
		End Try    
	End Function
	
	Public Function zapisUziv(uzivatel As String,heslo As String) 'zapise do suboru pouzivatela
		Try
		    Dim filePath As String
		    filePath = System.IO.Path.Combine(
		    My.Computer.FileSystem.SpecialDirectories.MyDocuments, "uziv" & uzivatel & ".txt")
		    My.Computer.FileSystem.WriteAllText(filePath, heslo, False)
		Catch fileException As Exception
		    Throw fileException
		End Try    
	End Function
	
	Public Function zapisPrihl(uzivatel As String) 'zapise toho, kto sa aktualne prihlasuje
		Try
		    Dim filePath As String
		    filePath = System.IO.Path.Combine(
		    My.Computer.FileSystem.SpecialDirectories.MyDocuments, "ktojeprihl.txt")
		    My.Computer.FileSystem.WriteAllText(filePath, uzivatel, False)
		Catch fileException As Exception
		    Throw fileException
		End Try    
	End Function
	
	Public Function vymazUziv(uzivatel As String) 'vymaze pouzivatela
		Try
		    Dim filePath As String
		    filePath = System.IO.Path.Combine(
		    My.Computer.FileSystem.SpecialDirectories.MyDocuments, "uziv" & uzivatel & ".txt")
		    My.Computer.FileSystem.DeleteFile(filePath)
		Catch fileException As Exception
		    Throw fileException
		End Try    
	End Function
	
	Public Function readUzivHeslo(uziv As String) As String 'vrati heslo pozadovaneho pouzivatela
		'Dim filePaths As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
		Dim allText As String
		Try
		   'filePaths = My.Computer.FileSystem.GetFiles(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
		   'For Each file As String In filePaths
		      allText = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/uziv" & uziv & ".txt")
		      'My.Computer.FileSystem.WriteAllText("bigfile.txt", allText, True)
		      'Next
		      Return allText
		Catch fileException As Exception
		   Throw fileException
		End Try  
	End Function
	
	Public Function readKtojeprihl() As String 'nacita, kto je aktualne prihlaseny v systeme
		'Dim filePaths As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
		Dim allText As String
		Try
		   'filePaths = My.Computer.FileSystem.GetFiles(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
		   'For Each file As String In filePaths
		      allText = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/ktojeprihl.txt")
		      'My.Computer.FileSystem.WriteAllText("bigfile.txt", allText, True)
		      'Next
		      Return allText
		Catch fileException As Exception
		   Throw fileException
		End Try  
	End Function
	
	Public Function ScreenResolution() 'skontroluje, ci ma obrazovka povolene rozlisenie, inak koniec
        Dim intX As Integer = Screen.PrimaryScreen.Bounds.Width
        Dim intY As Integer = Screen.PrimaryScreen.Bounds.Height
        If intX<800 Or intY<600 Then
        	showMessage("You need device with resolution minimum 800x600 pixels.")
        	Environment.Exit(-1)
        End If
	End Function
	
	Public Function showMessage(ByVal msg As String) 'vypise spravu msg
   ' Code is entered here that performs a calculation.
   ' Display a message box informing the user that the calculations 
   ' are complete.
      MessageBox.Show(msg, "Message", _
           MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk)
	End Function
	
	Public Function readRemote(addr As String) As String 'nacita vzdialeny web subor		
		Dim client As WebClient = New WebClient()
		Dim reader As StreamReader = New StreamReader(client.OpenRead(addr))
		Return reader.ReadToEnd
	End Function
	
	Public Function GenRandomInt(min As Int32, max As Int32) As Int32 'vrati nahodne cislo min max vratane
    	Static staticRandomGenerator As New System.Random
    	Return staticRandomGenerator.Next(min, max + 1)
	End Function
	
	Public Function citajOt(otazka As Short, test As Short) 'citaj otazku z daneho testu
		Dim allText As String
		Try
		      allText = My.Computer.FileSystem.ReadAllText(System.Windows.Forms.Application.StartupPath & "/data/otazkytxt/t" & test.ToString &"o" & otazka.ToString &".txt")
		      Return allText
		Catch ex As Exception
		   MsgBox(ex.Message)
		End Try  
	End Function
	
	Public Function citajOd(otazka As Short, test As Short) 'citaj odpoved z daneho testu
		Dim allText As String
		Try
		      allText = My.Computer.FileSystem.ReadAllText(System.Windows.Forms.Application.StartupPath & "/data/odptxt/t" & test.ToString & "d.txt")
		      'tu pokracuj treba rozbit do pola a nacitat v poradi t-1 odpoved
		      Dim testy() As String = allText.Split(New Char() {","c})		      
		      Return testy(otazka-1)
		Catch ex As Exception
		   MsgBox(ex.Message)
		End Try  
	End Function
	
	Public Function citajNevedel(uzivatel As String) As String 'citaj odpovede z daneho testu, ktore nevedel
		Dim allText As String
		Try
			If File.Exists(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/nevedel" & uzivatel & ".txt") Then
		      allText = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/nevedel" & uzivatel & ".txt")
		      'MsgBox(allText)
		      Return allText
			Else
				Return "t1o1,"	
			End If
		Catch ex As Exception
		   MsgBox(ex.Message)
		End Try  
	End Function
	
	
	
	'addr je http://www.server.com/readpost.php
	'postData je nejaky text, ktory sa odosle ako post
	Public Function sendPostRequest(addr As String, postData As String)
		Try
			Dim request As WebRequest = WebRequest.Create(addr)
            ' Set the Method property of the request to POST.  
            request.Method = "POST"  
            ' Create POST data and convert it to a byte array.  
            'Dim postData As String = "This is a test that posts this string to a Web server."  
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)  
            ' Set the ContentType property of the WebRequest.  
            request.ContentType = "application/x-www-form-urlencoded"  
            ' Set the ContentLength property of the WebRequest.  
            request.ContentLength = byteArray.Length  
            ' Get the request stream.  
            Dim dataStream As Stream = request.GetRequestStream()  
            ' Write the data to the request stream.  
            dataStream.Write(byteArray, 0, byteArray.Length)  
            ' Close the Stream object.  
            dataStream.Close()  
            ' Get the response.  
            Dim response As WebResponse = request.GetResponse()  
            ' Display the status.  
            'Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)  
            ' Get the stream containing content returned by the server.  
            dataStream = response.GetResponseStream()  
            ' Open the stream using a StreamReader for easy access.  
            Dim reader As New StreamReader(dataStream)  
            ' Read the content.  
            Dim responseFromServer As String = reader.ReadToEnd()  
            ' Display the content.  
            Console.WriteLine(responseFromServer)  
            ' Clean up the streams.  
            reader.Close()  
            dataStream.Close()  
            response.Close()
		Catch ex As Exception
			MsgBox(ex.Message)	
		End Try
	End Function
	
	Public Function pridajNevedene(retazec As String, uzivatel As String) 'prida otazky, ktore nevedel do suboru
		Try
			Dim filePath As String
			If Not File.Exists(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/nevedel"& uzivatel &".txt") Then
			    filePath = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/nevedel"& uzivatel &".txt"
			    My.Computer.FileSystem.WriteAllText(filePath, retazec, False)
			Else
				Dim nacitane As String
				nacitane = citajNevedel(uzivatel)
				nacitane += retazec
				Dim cesta As String
				cesta= My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/nevedel"& uzivatel &".txt"
			    My.Computer.FileSystem.WriteAllText(cesta, nacitane, False)
			End If
		Catch fileException As Exception
		    MsgBox(fileException.Message)
		End Try
	End Function
	
	Public Function citajKurzy(uzivatel As String) As String 'citaj kurzy daneho pouzivatela
		Dim allText As String
		Try
			If File.Exists(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/kurzy" & uzivatel & ".txt") Then
			allText = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/kurzy" & uzivatel & ".txt")
		      'MsgBox(allText)
		      Return allText
			Else
				Return ""
		    End If
		Catch ex As Exception
		   MsgBox(ex.Message)
		End Try  
	End Function
	
	Public Function citajKurz(kurz As String) 'citaj kurzy daneho pouzivatela
		Dim allText As String
		Try
			If File.Exists(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/kurz" & kurz & ".txt") Then
		      allText = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/kurz" & kurz & ".txt")
		      'MsgBox(allText)
		      Return allText
			Else
				Return ""
			End If
		Catch ex As Exception
		   MsgBox(ex.Message)
		End Try  
	End Function
	
	Public Function pridajKurzy(nazovKurzu As String, pridaneOtazky As String, uzivatel As String) 'prida zadany kurz
		Try
			Dim filePath As String
			If Not File.Exists(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/kurzy"& uzivatel &".txt") Then
			    filePath = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/kurzy"& uzivatel &".txt"
			    My.Computer.FileSystem.WriteAllText(filePath, nazovKurzu.Trim() & " ", False)						    
			Else
				Dim nacitane As String
				nacitane = citajKurzy(uzivatel)
				nacitane += nazovKurzu.Trim() & " "
				Dim cesta As String
				cesta= My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/kurzy"& uzivatel &".txt"
			    My.Computer.FileSystem.WriteAllText(cesta, nacitane, False)
			End If
			filePath = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/kurz"& nazovKurzu &".txt"
			My.Computer.FileSystem.WriteAllText(filePath, pridaneOtazky.Trim() & " ", False)						
		Catch fileException As Exception
		    MsgBox(fileException.Message)
		End Try
	End Function
	
	Function loadPicFromNet(url As String) 'nacita obrazok z netu a vrati ho pre picturebox
		Dim tClient as WebClient = new WebClient
		Dim tImage as Bitmap = Bitmap.FromStream(New MemoryStream(tClient.DownloadData(url)))
		'PictureBox1.Image = tImage
		Return tImage
	End Function
	
	'konsoliduje otazky, aby sa neopakovali, tie ktore nevedel v subore
	Public Function konsolidujOtazky(otazky As String) As String
		Dim pole() As String = otazky.Split(New Char() {","c})
		If pole.Length=0 Then
			Return ""
		End If
		Dim al As New ArrayList
		Dim ret As String
		'toto je uspornejsie a zafungovalo:
		For hodnota As Integer = 0 To pole.Length-2
			If Not al.Contains(pole(hodnota)) Then
				al.Add(pole(hodnota))
				ret = ret & pole(hodnota) & ","
			End If
		Next
		'preco toto nechcelo ist?:
		'nejako divne sa ten stroj sprava, je chraneny esetom
		'alebo nevidim pre oci nejaku chybu v kode
		'chcel som povyhadzovat duplicitne otazky takto:
		'For hodnota As Integer = 0 To pole.Length-2
			'For hodnota2 As Integer = 0 To pole.Length-2
			  'If hodnota<>hodnota2 Then 	
				'If String.Equals(pole(hodnota),pole(hodnota2)) Then
					'Replace(otazky, pole(hodnota) & ",", "")
				'End If
			  'End If
			'Next
		'Next
		
		If pole.Length > 200 Then 'ak uz mam otazok, ktore nevedel viac ako 200 idem nanovo
			ret = ""
		End If
		Return ret
	End Function
	
	'prepise nanovo nevedene otazky, ked su konsolidovane, aby sa neopakovali
	Public Function prepisNevedene(retazec As String, uzivatel As String) 'prida otazky, ktore nevedel do suboru
		Try
			Dim filePath As String
			    filePath = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/nevedel"& uzivatel &".txt"
			    My.Computer.FileSystem.WriteAllText(filePath, retazec, False)
		Catch fileException As Exception
		    MsgBox(fileException.Message)
		End Try
	End Function
	
	Public Function vratTEOT(pole As Array, co As String) As ArrayList
		Dim te As New ArrayList
		Dim ot As New ArrayList		
		For Each st As String In pole
			
			If st<>"" Then		
				If Char.IsDigit(st.Chars(1)) And Char.IsDigit(st.Chars(2)) Then
				Dim num As String = ""
				num = num & st.Chars(1) & st.Chars(2)				
				te.Add(Integer.Parse(num))
				
				End If
				If Char.IsDigit(st.Chars(1)) And Not Char.IsDigit(st.Chars(2)) Then
					Dim num2 As String = ""
					num2 = num2 & st.Chars(1)				
					te.Add(Integer.Parse(num2))					
				End If
				
				If st.Length=4 And Not st.Length=5 And Not st.Length=6 Then
					If Char.IsDigit(st.Chars(3)) Then
						Dim num As String = ""
						num = num & st.Chars(3) 
						ot.Add(Integer.Parse(num))
					End If
				End If
				
				If st.Length=5 And Not st.Length=6 And Not st.Length=4 Then
					If Char.IsDigit(st.Chars(4)) And Not Char.IsDigit(st.Chars(3)) Then
						Dim num As String = ""
						num = num & st.Chars(4) 
						ot.Add(Integer.Parse(num))
					End If
					If Char.IsDigit(st.Chars(4)) And Char.IsDigit(st.Chars(3)) Then
						Dim num As String = ""
						num = num & st.Chars(3) & st.Chars(4) 
						ot.Add(Integer.Parse(num))
					End If
				End If
				
				If st.Length=6 And Not st.Length=4 And Not st.Length=5 Then
					If Char.IsDigit(st.Chars(5)) And Char.IsDigit(st.Chars(4)) Then
						Dim num As String = ""
						num = num & st.Chars(4) & st.Chars(5) 
						ot.Add(Integer.Parse(num))
					End If
				End If
															
			End If
			Next
			
			If co ="te" Then
				Return te
			End If
			
			If co="ot" Then
				Return ot
			End If
    	
	End Function
	
	Public Function zistiNajpocetnejsi(pole As Array) As Integer
		Dim tst As New ArrayList 
		If pole.Length = 0 Then
			Return Me.GenRandomInt(1,35)
		End If
		For i As Integer = 0 To pole.Length-2
			If Char.IsDigit(pole(i).Chars(1)) And Char.IsDigit(pole(i).Chars(2)) Then
				Dim num As String = ""
				num = num & pole(i).Chars(1) & pole(i).Chars(2)				
				tst.Add(Integer.Parse(num))
				
			End If
			If Char.IsDigit(pole(i).Chars(1)) And Not Char.IsDigit(pole(i).Chars(2)) Then
				Dim num2 As String = ""
				num2 = num2 & pole(i).Chars(1)				
				tst.Add(Integer.Parse(num2))
				
            End If
        Next        
        'dalej pokusim sa usporiadat pole
		tst.Sort()
		Dim tst2 As New ArrayList
		Dim p As Integer
		For j = 0 To tst.Count-1
			For k = 0 To tst.Count-1
				If tst.Item(j)=tst.Item(k) Then
					p=p+1
				End If
			Next k			
			tst2.Add(p)
			p=0
		Next j
		Dim tst3 As New ArrayList
		For l = 0 To tst.Count-1
		tst3.add(tst2.Item(l))
		Next
		tst3.Sort()
		Dim outa As Integer = 1
		For m = 0 To tst.Count-1
			If tst2.Item(m)=tst3.Item(tst.Count-1) Then
				'MsgBox(tst.Item(m))
				If tst.Item(m)=36 Then
					Return Me.GenRandomInt(1,35)
				End If
				Return tst.Item(m)
			End If
		Next
       Return 1
	End Function
	
	
	'tuto mam odlozeny napad ako zabijat proces kvoli aktualizacii hlavneho A7
	Public Function killProccess()
		Dim myProcesses() As Process
    Dim myProcess As Process

    myProcesses = Process.GetProcessesByName("NameOfProcessAsString")

    Try

        If myProcesses.Length > 0 Then
            For Each myProcess In myProcesses
                If myProcess IsNot Nothing Then
                    myProcess.Kill()
                End If

            Next
        End If
    Catch ex As Exception
          MsgBox(ex.Message)
    End Try
	End Function
	
	'tu som si odlozil funkciu pre obsluhu webbrowsera
	Public Function linky()
		'Dim c
	    'Dim aLink As Object
	
	    'For Each aLink In WebBrowser1.Document.All.tags("A")
	        'List1.AddItem aLink.href
	    'Next aLink
	
	    'Open App.Path & "\urllist.txt" For Output As #1
	        'For c = 0 To List1.ListCount - 1
	            'Print #1, List1.List(c)
	        'Next
	        'Close #1
	        'WebBrowser1.Navigate "http://www.fatherofcents.com/"
	End Function
	
	'skontroluje, ci mam pripojenie na dany server:
	Public Function CheckForInternetConnection(httpurl As String) As Boolean
    Try
        Using client = New WebClient()
            Using stream = client.OpenRead(httpurl)
                Return True
            End Using
        End Using
    Catch
        Return False
    End Try
	End Function
	
	Public Function zmazVybranyKurz(menoKurzu As String)
		Try
		Dim kurzy As String = citajKurzy(readKtojeprihl()).ToString().Trim()
		Dim kurzyp As String() = kurzy.Split(New Char() {" "c})
		Dim kurzya As ArrayList = New ArrayList(kurzyp)
		Dim filePath As String
		'MsgBox(menoKurzu) 'tento zmazem
		kurzya.Remove(menoKurzu)
		'dalej skontrolujem, ci kurzya uz nie je prazdne
		'ak je prazdne, potrebujem vymazat kurzyuzivatel.txt aj kurzmeno.txt
		If kurzya.Count() = 0 Then
			
		    filePath = System.IO.Path.Combine(
		    My.Computer.FileSystem.SpecialDirectories.MyDocuments, "kurz" & menoKurzu & ".txt")
		    If File.Exists(filePath) Then
		    	My.Computer.FileSystem.DeleteFile(filePath)
		    End If
		    filePath = System.IO.Path.Combine(
		    My.Computer.FileSystem.SpecialDirectories.MyDocuments, "kurzy" & readKtojeprihl() & ".txt")
		    If File.Exists(filePath) Then
		    	My.Computer.FileSystem.DeleteFile(filePath)
		    End If
		Else
			'inak zmazem len meno kurzu kurzmeno.txt subor a zapisem kurzya oddelene medzerou do kurzyuzivatel.txt
			filePath = System.IO.Path.Combine(
		    My.Computer.FileSystem.SpecialDirectories.MyDocuments, "kurz" & menoKurzu & ".txt")
			If File.Exists(filePath) Then
		    	My.Computer.FileSystem.DeleteFile(filePath)
		    End If			
			Dim idemZapisatKurzy As String=""
			For Each k As String In kurzya
				idemZapisatKurzy &= k & " "
				filePath = System.IO.Path.Combine(
		    	My.Computer.FileSystem.SpecialDirectories.MyDocuments, "kurzy" & readKtojeprihl() & ".txt")
		    	My.Computer.FileSystem.WriteAllText(filePath, idemZapisatKurzy, False)
			Next
				
		End If
		Catch ex As Exception
			MsgBox(ex.Message)	
		End Try
	End Function
	
	Public Function ulozKnihuJazd(ktojeprihl As String, pridalText As String)
		Dim nacitane As String = ""
		Try
			If File.Exists(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/kj" & ktojeprihl & ".txt") Then
		      nacitane = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/kj" & ktojeprihl & ".txt")		      			
			End If
			
				nacitane =  pridalText.Trim()
				Dim filePath As String
			    filePath = System.IO.Path.Combine(
			    My.Computer.FileSystem.SpecialDirectories.MyDocuments, "kj" & ktojeprihl & ".txt")
			    My.Computer.FileSystem.WriteAllText(filePath, "", False)
			    My.Computer.FileSystem.WriteAllText(filePath, nacitane, False)
			
		Catch ex As Exception
		   MsgBox(ex.Message)
		End Try  
	End Function
	
	'len zistim, ci sa v retazci nachadza alebo nie cohladam
	Public Function najdeneCiNie(cohladam As String, kdehladam As String) As Boolean		
		Dim re As System.Text.RegularExpressions.Regex
        Dim m As System.Text.RegularExpressions.Match
        Dim t As String
        t = kdehladam
        re = New System.Text.RegularExpressions.Regex(cohladam)
        For Each m In re.Matches(t)
            Return True
        Next
        Return False
	End Function
	
	Public Function vytvorAdresar()
		Dim theContDir As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
        Dim newDir As String = "MyApp"

        Dim thePath As String = IO.Path.Combine(theContDir, newDir)

        If Not IO.Directory.Exists(thePath) Then
            Try
                IO.Directory.CreateDirectory(thePath)
            Catch UAex As UnauthorizedAccessException
                ' exception
            End Try
        End If
	End Function
	
	
End Class
