'////////////////////////////////////////////////////////////////////////
'// TRIVIA SCRIPT FOR 9.4
'// WRITTEN BY: Chriso
'////////////////////////////////////////////////////////////////////////

Dim Triv

'// Return Script Information
Sub Script(Name, Major, Minor, Build, Author, Commands, Description)
	Name = "Trivia"
	Major = 1
	Minor = 2
	Build = 0
	Author = "Chriso"
	Commands = "category, chances, leaderboard, resetscore, setcategory, setchances, score, trivia"
	Description = "This script allows you to host a trivia game in your channel through MirageBot."
End Sub

'// Called when the script is loaded for a particular bot
Sub Event_Load()
	CreateCommand "category", "Trivia", "Command_Category", "", "", "Return current trivia category", 0 , True
	CreateCommand "chances", "Trivia", "Command_Chances", "", "", "Return current trivia chances allowed", 0 , True
	'CreateCommand "dlcategory", "Trivia", "Command_DlCategory","","name", "Download a category file", 0, True
	CreateCommand "leaderboard", "Trivia", "Command_Leaderboard", "","", "Return top 5 trivia players", 0, True
	CreateCommand "resetscore", "Trivia", "Command_ResetScore", "", "", "Reset the trivia scores", 0, True
	CreateCommand "setcategory", "Trivia", "Command_SetCategory", "", "name", "Change trivia category", 0, True
	CreateCommand "setchances", "Trivia", "Command_SetChances", "", "#", "Change trivia chances amount", 0, True
	CreateCommand "score", "Trivia", "Command_Score", "", "[user]","Return your score, or someone elses", 0, True
	CreateCommand "trivia", "Trivia", "Command_Trivia", "", "mode", "Mode can be off or on", 0, True
	
	AddTimer "Trivia", "Trivia_Timer", 7000
	
	Set Triv = New Trivia
	Triv.Enabled = ReadConfig("Trivia", "Trivia")="Y"
	Triv.Chances = ReadConfig("Trivia", "Chances")
	Triv.Stats = LoadFile(GetBotPath & "TriviaStats.txt")
	If IsNumeric(Triv.Chances) = False Or Triv.Chances = "0" Then Triv.Chances = 4
	If Triv.SetCategory(ReadConfig("Trivia", "Category")) Then
		If Triv.UsingLocalFile Then
			AddChat vbGreen, "Trivia: Loaded " & Triv.LineCount & " questions from " & Triv.Category & "!"
		Else
			AddChat vbRed, "Trivia: Online Categories are no longer supported!"
			'AddChat vbGreen, "Trivia: Using online category: " & Triv.Category & "!"
		End If
	Else
		If Triv.UsingLocalFile Then
			AddChat vbRed, "Trivia: Category file '" & Triv.Category & "' does not exist!"
		Else
			AddChat vbRed, "Trivia: Online Categories are no longer supported!"
			'AddChat vbRed, "Trivia: Online category '" & Triv.Category & "' does not exist!"
		End If
	End If
End Sub

'// Called when the script is unloaded for a particular bot
Sub Event_Unload()

End Sub

'// Callback for "trivia" Command
Sub Command_Trivia(CS)
    Select Case LCase(CS.Message)
	Case "on"
		Triv.Enabled = True
		WriteConfig "Trivia", "Trivia", "Y"
		CS.Reply "Trivia is now on."
	Case "off"
		Triv.Enabled = False 
		WriteConfig "Trivia", "Trivia", "N"
		CS.Reply "Trivia is now off."
	Case "?"
		If Triv.Enabled Then
			CS.Reply "Trivia is currently on."
		Else
			CS.Reply "Trivia is currently off."
		End If
	End Select
End Sub

'// Callback for "leaderboard" Command
Sub Command_Leaderboard(CS)
	Dim I, LB, C, Buf
	LB = Triv.GetLeaderboard
	If UBound(LB) > 4 Then C = 4 Else C = UBound(LB)
	For I = 0 To C
		If Len(LB(I)) Then Buf = Buf & Replace(LB(I),"%"," (") & "), "
	Next
	If Len(Buf) = 0 Then
		Send2 "/me ~ No questions have been answered yet"
	Else
		If Right(Buf, 2) = ", " Then Buf = Left(Buf, Len(Buf)-2)
		Send2 "/me ~ Leaderboard: " & Buf
	End If
End Sub

'// Callback for "category" Command
Sub Command_Category(CS)
	If Len(Triv.Category) Then
		If Triv.UsingLocalFile Then
			CS.Reply "Trivia: Current category is " & Triv.Category & " (" & Triv.LineCount & " questions)"
		Else
			CS.Reply "Trivia: Online Categories are no longer supported!"
			'CS.Reply "Trivia: Current online category is " & Triv.Category
		End If
	Else
		CS.Reply "Trivia: Category not set!"
	End If
End Sub

'// Callback for "chances" Command
Sub Command_Chances(CS)
	If IsNumeric(Triv.Chances) Then
		CS.Reply "Trivia: Current amount of chances is " & Triv.Chances
	Else
		CS.Reply "Trivia: Chances not set!"
	End If
End Sub

'// Callback for "setcategory" Command
Sub Command_SetCategory(CS)
	If Triv.SetCategory(CS.Message) Then
		If Triv.UsingLocalFile Then
			AddChat vbGreen, "Trivia: Loaded " & Triv.LineCount & " questions from " & Triv.Category & "!"
		Else
			AddChat vbRed, "Trivia: Online Categories are no longer supported!"
			'AddChat vbGreen, "Trivia: Using online category: " & Triv.Category & "!"
		End If
	Else
		If Triv.UsingLocalFile Then
			AddChat vbRed, "Trivia: Category file '" & CS.Message & "' does not exist!"
		Else
			AddChat vbRed, "Trivia: Online Categories are no longer supported!"
			'AddChat vbRed, "Trivia: Online category '" & CS.Message & "' does not exist!"
		End If
	End If
End Sub

'// Callback for "dlcategory" Command
'!! No Longer Supported
'Sub Command_DlCategory(CS)
'	If Triv.DlCategory(CS.Message) Then
'		AddChat vbGreen, "Trivia: Downloaded category file to: " & GetFilePath & "Trivia\" & CS.Message & ".txt"
'	Else
'		AddChat vbRed, "Trivia: Error category does not exist or scInet is still busy."
'	End If
'End Sub

'// Callback for "setchances" Command
Sub Command_SetChances(CS)
	If IsNumeric(CS.Message) Then
		Triv.Chances = CS.Message
		WriteConfig "Trivia", "Chances", Triv.Chances
		CS.Reply "Trivia: Chances set to: " & Triv.Chances
	Else
		CS.Reply "Trivia: That is not a number!"
	End If
End Sub

'// Callback for "resetscore" Command
Sub Command_ResetScore(CS)
	Triv.Stats = ""
	SaveFile GetBotPath & "TriviaStats.txt", Triv.Stats
	CS.Reply "Trivia: Scores reset!"
End Sub

'// Callback for "score" Command
Sub Command_Score(CS)
	Dim Score
	If Len(CS.Message) Then
		Score = Triv.GetScore(CS.Message)
		If Score > 0 Then
			CS.Reply "Trivia: " & CS.Message & "'s score is: " & Score
		Else
			CS.Reply "Trivia: " & CS.Message & " has not answered any questions yet."
		End If
	Else
		Score = Triv.GetScore(CS.Username)
		If Score > 0 Then
			CS.Reply "Trivia: Your score is: " & Score
		Else
			CS.Reply "Trivia: You have not answered any questions yet."
		End If
	End If
End Sub

'// Called when a user speaks
Sub Event_UserTalk(CE)
	If Triv.Enabled Then
		Dim Ans
		Ans = Triv.GetAnswer
		If Triv.SolveTrivia(CE.Message) Then
			Triv.IncreaseScore CE.Username
			Send "/cq"
			Send2 "/me Congratulations " & CE.Username & "! Answer was: " & Ans & "! Your score: " & Triv.GetScore(CE.Username) & "!"
		End If
	End If
End Sub

Sub Trivia_Timer()
	If Triv.Enabled Then
		If GetBot.IsOnline Then
			If Triv.HintCount = 0 Then
				Dim Q
				Q = Triv.GetQuestion	
				If Len(Q) Then
					Send2 "/me ~ Question: " & Q
					Triv.HintCount = 1
				End If
			Else
				If CInt(Triv.Chances) > CInt(Triv.HintCount) Then
					If Triv.IsBusy Then
						Send2 "/me ~ Hint: " & Triv.GetHint
						Triv.HintCount = Triv.HintCount + 1
					End If
				Else
					If Triv.IsBusy Then
						Send "/cq"
						Send2 "/me ~ Times Up! Answer was: " & Triv.GetAnswer
					End If
					Triv.SolveTrivia Triv.GetAnswer
				End If
			End If
		Else
			Triv.SolveTrivia Triv.GetAnswer
		End If
	Else
		If Triv.IsBusy Then Triv.SolveTrivia Triv.GetAnswer
	End If
End Sub

Class Trivia

	Public Enabled, Category, CatFile, Lines
	Public IsBusy, HintCount, Chances
	Public Stats, UsingLocalFile
	Public CurAnswer, CurHint, CurQuestion

	Public Function LineCount()
	On Error Resume Next
		If Len(Lines(0)) > 0 Then
			LineCount = UBound(Lines) + 1
		End If
	End Function

    Public Function IncreaseScore(Username)
		Username = GetBot.GetAccount(Username)
		If Left(Username,1) = "*" Then Username = Mid(Username,2)
        Dim I
        I = InStr(LCase(Stats), LCase(Username) & "%")
        If I <> 0 Then
            Dim Value
            Value = Mid(Stats, I + Len(Username) + 1)
            Value = Split(Value, vbNewLine)(0)
            If IsNumeric(Value) = False Then Value = 0
            Stats = Left(Stats, I + Len(Username)) & (Value + 1) & Mid(Stats, I + Len(Username) + 1 + Len(Value))
        Else
			If Right(Stats,2) = vbNewLine Then
				Stats = Stats & Username & "%1" & vbNewLine
			Else
				If Len(Stats) Then
					Stats = Stats & vbNewLine & Username & "%1" & vbNewLine
				Else
					Stats = Username & "%1" & vbNewLine
				End If
			End If
		End If
		SaveFile GetBotPath & "TriviaStats.txt", Stats
    End Function

	Public Function GetLeaderboard()
		Dim SL, LB, I
		ReDim LB(0)
		SL = Split(Stats, vbNewLine)
		For I = 0 To UBound(SL)
			Dim TL
			TL = Split(SL(I), "%")
			If UBound(TL) = 1 Then
				If Len(LB(0)) = 0 Then
					LB(0) = SL(I)
				Else
					Dim X, Done
					Done = False
					For X = 0 To UBound(LB)
						Dim XL
						XL = Split(LB(X), "%")
						If CInt(TL(1)) > CInt(XL(1)) Then
							ReDim Preserve LB(UBound(LB)+1)
							'Copy to Temporary Array
							Dim N, NB
							ReDim NB(UBound(LB))
							For N = X To UBound(LB)-1
								NB(N+1) = LB(N)
							Next 
							'Move items back
							For N = X+1 To UBound(LB)
								LB(N) = NB(N)
							Next
							'Set current item
							LB(X) = SL(I)
							Done = True
							Exit For
						End If
					Next
					'Item not able to be inserted
					'Add to end
					If Not Done Then
						ReDim Preserve LB(UBound(LB)+1)
						LB(UBound(LB)) = SL(I)
					End If
				End If
			End If
		Next
		GetLeaderBoard = LB
	End Function

	Public Function GetScore(Username)
		Username = GetBot.GetAccount(Username)
		If Left(Username,1) = "*" Then Username = Mid(Username,2)
        Dim I
        I = InStr(LCase(Stats), LCase(Username) & "%")
        If I <> 0 Then
            Dim Value
            Value = Mid(Stats, I + Len(Username) + 1)
            Value = Split(Value, vbNewLine)(0)
            If IsNumeric(Value) = False Then Value = 0
            GetScore = Value
        Else
			GetScore = 0
		End If
	End Function

	Public Function SetCategory(NewCat)
		If LCase(Right(NewCat,4)) = ".txt" Then
			Dim CF
			UsingLocalFile = True
			CreateFolder GetFilePath & "Trivia"
			CF = GetFilePath & "Trivia\" & NewCat 
			If IsFile(CF) Then
				Category = NewCat
				CatFile = CF
				WriteConfig "Trivia", "Category", Category
				SetCategory = True
				MyLines = Split(LoadFile(CatFile), vbNewLine)
				Dim I, C
				ReDim Lines(UBound(MyLines))
				For I = 0 To UBound(MyLines)
					If InStr(MyLines(I),"|") Then
						Lines(C) = MyLines(I)
						C = C + 1
					End If
				Next
				ReDim Preserve Lines(C-1)
			Else
				ReDim Lines(0)
				SetCategory = False
			End If
		End If
		'!! No Longer Supported
		'Else
		'	If Not scInet.StillExecuting Then
		'		Dim RetVal
		'		RetVal = scInet.OpenURL("http://trivia.bnetdev.net/bot/?query=list")
		'		If InStr(LCase(RetVal), LCase(NewCat)) Then
		'			Category = NewCat
		'			WriteConfig "Trivia", "Category", Category
		'			UsingLocalFile = False
		'			SetCategory = True
		'		Else
		'			SetCategory = False
		'		End if
		'	End If
		'End If
	End Function
	
	'!! No Longer Supported
	'Public Function DlCategory(Name)
	'	Dim RetVal
	'	DlCategory = False
	'	If scInet.StillExecuting Then Exit Function
	'	RetVal = scInet.OpenURL("http://trivia.bnetdev.net/bot/?query=cat&name=" & Name)
	'	If Len(RetVal) Then
	'		RetVal = Replace(RetVal, "<br/>", "<br />")
	'		RetVal = Replace(RetVal, "<br />", vbNewLine)
	'		RetVal = Trim(RetVal)
	'		SaveFile GetFilePath & "Trivia\" & Name & ".txt", RetVal
	'		DlCategory = True
	'	End If
	'End Function
	
	Public Function GetAnswer()
		GetAnswer = CurAnswer
	End Function

	Public Function GetHint()
		Dim Complete, Count, Threshold
		'Get Hint
		If Len(CurHint) = 0 Then CurHint = String(Len(CurAnswer), "-")
		'Get Threshold
		Threshold = Len(CurAnswer) \ (Chances)
		'Check Threshold
		If Threshold > 0 Then
			'Look for Dashes
			Do Until Complete = True
				'Check for Dashes
				If InStr(CurHint, "-") <> 0 Then
					'Get random position
					Dim I
					Randomize Timer
					I = Int(Rnd * Len(CurAnswer)) + 1
					'Check random position is a dash
					If Mid(CurHint, I, 1) = "-" Then
						'Reveal this Character
						CurHint = Left(CurHint, I-1) & Mid(CurAnswer, I, 1) & Mid(CurHint, I + 1)
						'Increment Count
						Count = Count + 1
					End If
					'Check if a quarter of the characters were revealed
					If Count = Threshold Then Complete = True
				Else
					Complete = True
				End If
			Loop
		End If
		'Return
		GetHint = CurHint
	End Function

	Public Function GetQuestion()
		'Check if game in progress
		If IsBusy = False Then
			If UsingLocalFile Then
				'Get a new question
				Dim I
				Randomize
				I = Int(Rnd * LineCount)
				CurHint = ""
				CurQuestion = Trim(Split(Lines(I), "|")(0))
				CurAnswer = Trim(Split(Lines(I), "|")(1))
				HintCount = 0
				IsBusy = True
			'!! No Longer Supported
			'Else
			'	If Not scInet.StillExecuting Then
			'		Dim RetVal
			'		RetVal = scInet.OpenURL("http://trivia.bnetdev.net/bot/?query=random&name=" & Category)
			'		If InStr(RetVal, "|") Then
			'			CurQuestion = Trim(Split(RetVal, "|")(0))
			'			CurAnswer = Trim(Split(RetVal, "|")(1))
			'			CurAnswer = Replace(CurAnswer, "<br />", "")
			'			CurAnswer = Replace(CurAnswer, "<br/>", "")
			'			CurQuestion = Replace(CurQuestion, "<br />", "")
			'			CurQuestion = Replace(CurQuestion, "<br/>", "")
			'			CurHint = ""
			'			HintCount = 0
			'			IsBusy = True
			'		Else
			'			AddChat vbRed, "Unable to get valid question from online category."
			'		End If
			'	End If
			End If
		End If
		'Return current question
		GetQuestion = CurQuestion
	End Function

	Public Function SolveTrivia(Given)
		SolveTrivia = False
		If LCase(Trim(Given)) = LCase(Trim(CurAnswer)) Then
			SolveTrivia = True
			HintCount = 0
			IsBusy = False
			CurQuestion = ""
			CurAnswer = ""
			CurHint = ""
		End If
	End Function

	Public Function IsFile(f)
		Dim fso
		Set fso = CreateObject("Scripting.FileSystemObject")
		IsFile = fso.FileExists(f)
	End Function

	Public Function CreateFolder(f)
		Dim fso
		Set fso = CreateObject("Scripting.FileSystemObject")
		If fso.FolderExists(f) = False Then fso.CreateFolder f
	End Function

End Class