Const adKeyPrimary = 1
Const adInteger = 3
Const adVarChar = 202
Const adBoolean = 11 
Const adDate = 7

Const adOpenForwardOnly = 0 
Const adOpenKeyset = 1
Const adOpenDynamic = 2
Const adOpenStatic = 3 

Const adLockReadOnly = 1
Const adLockPessimistic = 2
Const adLockOptimistic = 3
Const adLockBatchOptimistic = 4 

Const adCmdUnknown = &H0008
Const adCmdText = &H0001
Const adCmdTable = &H0002
Const adCmdStoredProc = &H0004 

Const dbProvider = "Provider=Microsoft.JET.OLEDB.4.0;Data Source="

Private Gnome

Sub Script(Name, Major, Minor, Build, Author, Commands, Description)
	Name = "DroidGnome"
	Major = 1
	Minor = 0
	Build = 1
	Author = "Droid"
	Commands = "pingstats"
	Description = "DroidGnome is your own personal PingGnome that will record and query ping stats for the channels you go to."
End Sub

Sub Event_Load()
	Set Gnome = New DroidGnome
	Gnome.File = GetDataPath() & "droidgnome1.mdb"
	Gnome.CreateDatabase
    CreateCommand "pingstats", "DroidGnome", "Command_PingStats", "ps", "user", "Queries DroidGnome database for ping statistics.", 0, True
    AddChat RGB(255, 236, 179), "DroidGnome loaded."
End Sub

Sub Event_Unload()
	Set Gnome = Nothing
	AddChat RGB(159, 140, 83), "DroidGnome unloaded."
End Sub

Sub Command_PingStats(CS)
    If CS.IsConsole = True And CS.Message = vbNullString Then
		QueryName = GetBot.Config.Username
	Else
		If CS.Message = vbNullString Then QueryName = CS.Username Else QueryName = CS.Message
	End If
	If Not ValidateName(QueryName) Then
		CS.Reply "Invalid account."
		Exit Sub
	End If
	Gnome.Query QueryName
	If Gnome.PingCount = -2 Then 
		CS.Reply "I have no data for [" & QueryName & "]."
	Else
		If Gnome.PingCount <> 1 Then pluralTime = "s"
		CS.Reply QueryName & " [" & Gnome.LastProduct & "] [Last:" & Gnome.LastPing & "ms] [Lowest:" & Gnome.LowPing & "ms] [Highest:" & Gnome.HighPing & "ms] [Avg:" & Gnome.AvgPing & "ms] [Seen: " & Gnome.PingCount & " time" & pluralTime & " since " & Gnome.CreationDate & "] [Last entry: " & Gnome.LastSeen & " (" & Gnome.SeenDiff & ")]"		
    End If
End Sub

Sub Event_UserJoin(CE)
	Gnome.Add GetUser(CE.Username).Account, CE.Ping, GetUser(CE.Username).Client, Now()
End Sub

Sub Event_UserPresent(CE)
	Gnome.Add GetUser(CE.Username).Account, CE.Ping, GetUser(CE.Username).Client, Now()
End Sub

'Databasing
Function CheckFileExist(Filename)
	Set FSO = CreateObject("Scripting.FileSystemObject")
	CheckFileExist = FSO.FileExists(FileName)
	Set FSO = Nothing
End Function

Function CheckDateCreated(Filename)
	Set FSO = CreateObject("Scripting.FileSystemObject")
	CheckDateCreated = Split(FSO.GetFile(Filename).DateCreated)(0)
	Set FSO = Nothing
End Function

Function ValidateName(Name)
	If Instr(1, Name, "'") Then ValidateName = False Else ValidateName = True
End Function

Class DroidGnome
	Private m_File, m_CreationDate, RS, m_Ping(6)
	
	Public Property Let File(value)
		m_File = value
	End Property
	
	Public Property Get File
		File = m_File
	End Property
	
	Public Property Get HighPing
		HighPing = m_Ping(0)
	End Property
	
	Public Property Get LowPing
		LowPing = m_Ping(1)
	End Property
	
	Public Property Get AvgPing
		AvgPing = m_Ping(2)
	End Property
	
	Public Property Get PingCount
		PingCount = m_Ping(3)
	End Property

	Public Property Get LastPing
		LastPing = m_Ping(4)
	End Property
	
	Public Property Get LastProduct
		LastProduct = m_Ping(5)
	End Property
	
	Public Property Get LastSeen
		LastSeen = Split(m_Ping(6))(0)
	End Property
	
	Public Property Get SeenDiff
		SecondsAgo = DateDiff("s", m_Ping(6), Now)
        DaysAgo = CLng(SecondsAgo / 86400)
        SecondsAgo = SecondsAgo - DaysAgo * 86400
        HoursAgo = CLng(SecondsAgo / 3600)
        SecondsAgo = SecondsAgo - HoursAgo * 3600
        MinutesAgo = CLng(SecondsAgo / 60)
        SecondsAgo = SecondsAgo - MinutesAgo * 60
        
        If SecondsAgo < 0 Then MinutesAgo = MinutesAgo - 1: SecondsAgo = SecondsAgo + 60
        If MinutesAgo < 0 Then HoursAgo = HoursAgo - 1: MinutesAgo = MinutesAgo + 60
        If HoursAgo < 0 Then DaysAgo = DaysAgo - 1: HoursAgo = HoursAgo + 24
        
        If DaysAgo <> 0 Then FinalDiff = DaysAgo & " days, "
        If DaysAgo = 1 Then FinalDiff = Replace(FinalDiff, "days", "day")
        If HoursAgo <> 0 Then FinalDiff = FinalDiff & HoursAgo & " hours, "
        If HoursAgo = 1 Then FinalDiff = Replace(FinalDiff, "hours", "hour")
        If MinutesAgo <> 0 Then FinalDiff = FinalDiff & MinutesAgo & " minutes, and "
        If MinutesAgo = 1 Then FinalDiff = Replace(FinalDiff, "minutes", "minute")
        FinalDiff = FinalDiff & SecondsAgo & " seconds ago"
        If SecondsAgo = 1 Then FinalDiff = Replace(FinalDiff, "seconds", "second")
        
        SeenDiff = FinalDiff
	End Property
	
	Public Property Get CreationDate
		CreationDate = m_CreationDate
	End Property
	
	Public Property Set CreationDate(value)
		m_CreationDate = value
	End Property
	
	Private Property Get Connection
		Connection = dbProvider & m_File
	End Property
	
	Private Sub Class_Initialize()
		Set RS = CreateObject("ADODB.Recordset")
	End Sub
	
	Private Sub Class_Terminate()
		Set RS = Nothing
	End Sub
		
	Public Function Add(Pingname, Ping, Product, SeenDate)
		With RS
			.Open "SELECT * FROM Usernames", Connection, adOpenStatic, adLockOptimistic
			QueryName = "Username = '" & Pingname & "'"
			.Find QueryName
			If .EOF Then
				.Close
				.Open "Usernames", Connection, adOpenKeyset, adLockOptimistic, adCmdTable
				.AddNew
				RS("username") = Pingname
				.Update
				UserID = RS("id")
			Else
				UserID = RS("id")
			End If
			.Close
			.Open "Pings", Connection, adOpenKeyset, adLockOptimistic, adCmdTable
			.AddNew
			RS("id") = UserID
			RS("ping") = Ping
			RS("product") =  Product
			RS("seendate") = SeenDate
			.Update
			.Close
		End With
	End Function
	
	Public Sub Query(Pingname)
		With RS
			.Open "SELECT Usernames.username, Pings.ping, Pings.product, Pings.seendate FROM (Pings INNER JOIN Usernames ON Pings.id = Usernames.id) WHERE (Usernames.username = '" & Pingname & "') ORDER BY Pings.seendate", Connection, adOpenStatic, adLockOptimistic
			If .EOF Then
				For i = 0 To UBound(m_Ping)
					m_Ping(i) = -2
				Next
			Else
				m_Ping(0) = RS("ping")
				m_Ping(1) = RS("ping")
				m_Ping(2) = 0
				m_Ping(3) = .RecordCount
				Do While Not .EOF
					If RS("ping") > m_Ping(0) Then m_Ping(0) = RS("ping") Else If RS("ping") < m_Ping(1) Then m_Ping(1) = RS("Ping")
					m_Ping(2) = m_Ping(2) + RS("ping")
					.MoveNext
				Loop
				.MoveLast
				m_Ping(4) = RS("ping")
				m_Ping(5) = RS("product")
				m_Ping(6) = RS("seendate")
				m_Ping(2) = CInt(m_Ping(2) / m_Ping(3))
			End If
			.Close
		End With
	End Sub
	
	Public Sub CreateDatabase()
		If CheckFileExist(m_File) Then 
			m_CreationDate = CheckDateCreated(m_File)
			Exit Sub
		End If
		Set Catalog = CreateObject("ADOX.Catalog")
		Set UserTable = CreateObject("ADOX.Table")
		Set PingTable = CreateObject("ADOX.Table")
		
		Catalog.Create dbProvider & m_File
		
		UserTable.ParentCatalog = Catalog
		UserTable.Name = "Usernames"
		UserTable.Columns.Append "id", adInteger
		UserTable.Columns("id").Properties("Autoincrement").Value = True
		UserTable.Columns.Append "username", adVarChar, 30
		UserTable.Keys.Append "PrimaryKey", adKeyPrimary, "id"
		Catalog.Tables.Append UserTable
		
		PingTable.ParentCatalog = Catalog
		PingTable.Name = "Pings"
		PingTable.Columns.Append "pingid", adInteger
		PingTable.Columns.Append "id", adInteger
		PingTable.Columns.Append "ping", adInteger
		PingTable.Columns.Append "product", adVarChar, 4
		PingTable.Columns.Append "seendate", adDate
		PingTable.Columns("pingid").Properties("Autoincrement").Value = True
		PingTable.Keys.Append "PrimaryKey", adKeyPrimary, "pingid"
		Catalog.Tables.Append PingTable
		
		m_CreationDate = CheckDateCreated(m_File)
		
		Set UserTable = Nothing
		Set PingTable = Nothing
		Set Catalog = Nothing
	End Sub
End Class