BrighteonUpload:
;------------------------------------------------
CurrentSite := "Brighteon"
SaveOrPostProgress(Message:="Starting Upload",PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
Status := NavigateFromBaseURLTo("https://www.brighteon.com/dashboard/video-upload")
if(Status)
Return


JSBrighteonVideoDescription := FormatTextToJSText(VideoDescription)
; Msgbox % "JSBrighteonVideoDescription: " JSBrighteonVideoDescription

; descriptions longer than 5k characters just fail to get input so trim them to below 5000 characters
if(StrLen(VideoDescription) >= 5000){
	BrighteonVideoDescription := SubStr(VideoDescription, 1, 4800)
	BrighteonVideoDescription .= "...."
	JSBrighteonVideoDescription := FormatTextToJSText(BrighteonVideoDescription) 

	if(StrLen(JSBrighteonVideoDescription) > 5000){
		BrighteonVideoDescription := SubStr(VideoDescription, 1, 4500)
		BrighteonVideoDescription .= "...."
		JSBrighteonVideoDescription := FormatTextToJSText(BrighteonVideoDescription) 
	}
}




Message = Checking Login Status
SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile")
try CurrentTab := driver.url
if(InStr(CurrentTab, "login")) ; we're logged out
{

	Message = Currently Logged Out`nClosing out of any popups that might appear before clicking Login button
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile")

	Xpath = //body/div[@id='__next']/div[@id='modal-root']/div[2]/div[1]/div[1]//*[local-name()='svg']
	Status := Selenium_LoopToClickXpath(Xpath:=Xpath,NumOfLoops:=1,SleepLength:=100)

	Xpath = //body/div[@id='__next']/div[@id='modal-root']/div/div/div[1] ; get our free newsletter
	Status := Selenium_LoopToClickXpath(Xpath:=Xpath,NumOfLoops:=1,SleepLength:=100)

	; If newsletter pop up exists then close it.
	Xpath = //div[@class='overlay__close inside']
	Status := Selenium_LoopToClickXpath(Xpath:=Xpath,NumOfLoops:=1,SleepLength:=100)

	; Try clicking the login button, sometimes this will auto log you back in without having to input credentials
	xpath = //a[normalize-space()='Log In']
	Status := Selenium_LoopToClickXpath(Xpath:=Xpath,NumOfLoops:=1,SleepLength:=100)
	; DevModeMsgBox(Status)


	Message = Checking Login Status
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile")

	try PageURL := driver.url
	if(InStr(PageURL, "auth.brighteon.com/login?state")){ ; we're logged out and need to manually log back in


	if(AutoLogin){
		Message = Trying to Log Back In
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile, DiscordErrorLogging")

		; js = return document.querySelector("input[placeholder='username/email']").value;
		; status := try driver.executeScript(JS)			;Execute Javascript

		; sleep, 5000
		; Msgbox % "status: " status

		; if(StrLen(Status) > 0){
			; msgbox, clicking login button
			Xpath = //a[normalize-space()='Log In'] ; click login button at top right of page
			Status := Selenium_LoopToClickXpath(Xpath:=Xpath,NumOfLoops:=2,SleepLength:=1000) 

			; sleep, 2000
			Xpath = //button[@type='submit'] ; click login button on login page
			Status := Selenium_LoopToClickXpath(Xpath:=Xpath,NumOfLoops:=6,SleepLength:=1000)
			try driver.executeScript("return document.readyState").equals("complete") 

			sleep, 2000
			; }


		}
		else, {
			SaveOrPostProgress(Message:="Login Expired. Please log back in",PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
			SaveDriverURLOFErrorPage()
			Return
		}
	}
}



Message = Navigating to Upload Page
SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile")

; Navigate to Upload Page 
try driver.executeScript("window.location = 'https://www.brighteon.com/dashboard/video-upload'") ;navigate using javascript 

try driver.executeScript("return document.readyState").equals("complete") 

TabURl := GetCurrentTabURlBase()
Message = Current Tab URL: %TabURL%
SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")

; Click out of the "Support free speech" pop-up if it pops up
Xpath = //body/div[@id='__next']/div[@id='modal-root']/div/div/div[1]//*[local-name()='svg']
try driver.FindElementByXPath(Xpath).click()


CheckForAlerts()

if(BrighteonUploadAttempt){
	Sleep, 2000
}

Message = Uploading Video
SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile")
; Upload Video
Xpath = //input[@type='file']
Status := Selenium_LoopToSendValueToXpath(Xpath:=Xpath,NumOfLoops:=2,SleepLength:=1000,StringTextContent:=VideoFilepath)
if(Status){
	Message = Failed to Upload Video, Please check Login Status
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	SaveDriverURLOFErrorPage()
	Return
}


loop, 3 {
	if(A_index = 3){
		Message = Failed to input Video Title
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
		Return
	}


	; Input Title of the Video
	Xpath = //input[@id='name']
	try driver.FindElementByXPath(Xpath).SendKeys(VideoTitle)     ;Sends Variable to an Xpath Item


	; click into keyword box to get focus away from title element and see if the video title registers with website
	xpath = //input[@id='keywords']
	try driver.FindElementByXPath(Xpath).click()

	sleep, 500

	; check if title got input
	js = return document.querySelector("#name").value; 
	try, status := driver.executeScript(js)
	if(status = "")
	continue

	js = return document.querySelector("#name").value; 
	try, status := driver.executeScript(js)

	Message = Title that got input: %status%
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
	break

}


TooltipThis("Inputting Video Description")



; Attempt to input video description a couple of times
Loop, 10 {
	if(A_index = 10){
		Message = Failed to input Video Description after 10 attempts. 
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")

		if(!BrighteonUploadAttempt){

			Message = Re-Trying Entire Upload
			SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")

			BrighteonUploadAttempt := 2
			goto, BrighteonUpload
		}

		Message = Brighteon Upload Failed after 2 seperate individual attempts. Please try uploading manually and report any errors.
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")

		SaveDriverURLOFErrorPage()
		Return
	}

	Message = Inputting Description. Attempt Number: %A_index%
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
	; SaveOrPostProgress(Message:=Message,PostType:="DiscordErrorLogging")

	Xpath = //div[@class='e-content e-lib e-keyboard']
	Status := Selenium_LoopToSendValueToXpath(Xpath:=Xpath,NumOfLoops:=2,SleepLength:=1000,StringTextContent:=VideoDescription)
	if(Status){
		SaveOrPostProgress(Message:="Failed to input Video Description",PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
		; SaveDriverURLOFErrorPage()
		; Return
	}

	sleep, 5000


	js = return document.querySelector("div[class='e-content e-lib e-keyboard'] p").innerText;
	try Input_Description := driver.executeScript(JS)            ;Execute Javascript

	Input_DescriptionStrLen := StrLen(Input_Description)
	Message = Length of Description that got input: %Input_DescriptionStrLen%
	SaveOrPostProgress(Message:=Message,PostType:="ErrorLoggingTextFile,DiscordErrorLogging")

	; if text in description box is longer than x chars, then description input worked
	if(StrLen(Input_Description) > 15){
		Input_Description := SubStr(Input_Description, 1, 20)
		Message = Description that got input: %Input_Description% ...
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
		Break
	}
}


; Thumbnail 
if(VideoThumbFilepath != "") {
	TooltipThis("Uploading Thumbnail")
	Xpath = //input[@type='file']
	Status := Selenium_LoopToSendValueToXpath(Xpath:=Xpath,NumOfLoops:=2,SleepLength:=1000,StringTextContent:=VideoThumbFilepath)
	if(Status){
		Message = Failed to Upload Thumbnail
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	}
}


; Brighteon has a max of 25 for tags. 
if(ArrayOfVideoTags.Length() > 25){
	Loop % 24 {
		BrighteonKeywords := ArrayOfVideoTags[A_Index]
	}
}
else,
BrighteonKeywords := VideoTags



TooltipThis("Inputting Keywords")
Loop, 5 {
	XPath = //input[@id='keywords']
	try driver.FindElementByXPath(Xpath).SendKeys(BrighteonKeywords)     ;Sends Variable to an Xpath Item
	catch e {
		Message = Error (E#2312)`nVideo Uploaded but Unable to Input Video Tags
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	}

	; click into video title to get focus away from inputbox
	Xpath = /html/body/div/section[2]/div[2]/div/form/div[1]/div[1]/div[2]/div[1]/div/input
	try, driver.FindElementByXPath(Xpath).click()    ;Sends Variable to an Xpath Item

	; check that the tags got input
	js = return document.querySelector("#keywords").value; 
	try, status := driver.executeScript(js)
	if(!status){
		Message = Failed to input tags.
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
	}
	else, {
		Message = Tags that got input: %status%
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
		break
	}


}

; double check on video description after inputting tags
js = return document.querySelector("div[class='e-content e-lib e-keyboard'] p").innerText;
try Input_Description := driver.executeScript(JS)            ;Execute Javascript

; if text in description box is longer than x chars, then description input worked
if(StrLen(Input_Description) > 5){
	SaveOrPostProgress(Message:="Video Description second double check was successful",PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
}
else, {
	SaveOrPostProgress(Message:="Secondary video description check failed",PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	Return
}



TooltipThis("Waiting for Video to Finish Uploading")
Loop, %Number_of_loops_to_Check_Upload_status% {
	sleep, %Time_Between_Loops_Upload_Status%

	; Get progress status through javascript
	jsCheck = return document.getElementsByClassName('video-upload--details')[0].textContent;
	try ProgressStatus := driver.executeScript(jsCheck)  

	if(ProgressStatus = ""){
		Message = Failed to Grab Video Upload Status. Upload Most Likely Failed
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
		SaveDriverURLOFErrorPage()
		Return
	}

	if(InStr(ProgressStatus, "Upload complete.")){
		Break
	}

	; Pull out progress Percentage from full string
	UploadPercent := StrSplit(ProgressStatus, "(")
	UploadPercent := UploadPercent[2]
	UploadPercent := StrSplit(UploadPercent, ")")
	UploadPercent := UploadPercent[1]

	; Message = Waiting for Video to Finish Uploading`nCurrent Upload Status: %UploadPercent%
	; SaveOrPostProgress(Message:=Message,PostType:="Tooltip")

	Status := Check_For_Stuck_Video_Upload(A_index, UploadPercent)
	if(Status = "Failed")
	Return
}


; "Save Now" button
js = return document.querySelector("button[class='mr-2 btn btn-primary btn-sm']").textContent; 
try, status := driver.executeScript(js)
if(!InStr(status, "Save Video")){
	Message = Save Video Button is not clickable. Please check page for errors.
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	SaveDriverURLOFErrorPage()
	Return
}


; Save Video button
TooltipThis("Clicking Save Video Button to finalize Upload")
try BrighteonUploadPageURL := driver.url
try driver.executeScript("return document.readyState").equals("complete") ; wait until page loads completely before proceeding


TooltipThis("Waiting for Result page to finish loading")
Loop, 10 { ; 5 loops of 1 minute each
	if(A_index = 10){
		Message = Upload Failed: Clicking "Save Video" did not Finalize the Upload
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")  
		SaveDriverURLOFErrorPage()
		Return ; Break out of gosub
	}
	js = document.getElementsByClassName('mr-2 btn btn-primary btn-sm')[0].click(); ; Save Video Button
	try driver.executeScript(js)
	driver.executeScript("return document.readyState").equals("complete") ; wait until page loads completely before proceeding

	sleep, 5000 ; 30 seconds
	try CurrentURL := driver.url
	if(BrighteonUploadPageURL != CurrentURL)
	Break
}


Message = Trying to Grab Newest Video's URL
SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile")
sleep, 2000

; Navigate to Videos page to make sure it's refreshed with latest video
try driver.Get("https://www.brighteon.com/dashboard/videos")	;Open selected URL
try driver.executeScript("return document.readyState").equals("complete") ; wait until page loads completely before proceeding
sleep, 2000


; Get First word in video title to use in grabbing video URL
VideoTitleArray := StrSplit(VideoTitle, " ")
; Iterate from 1 to the end of the array:
Loop % VideoTitleArray.Length(){
	VideoTitleLongWord := VideoTitleArray[A_Index]
	; VideoTitleFirstWord := StrReplace(VideoTitleFirstWord, "_","-")
	if(StrLen(VideoTitleLongWord) > 4)
	Break

}


Message = VideoTitleLongWord: %VideoTitleLongWord%
SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
; SaveOrPostProgress(Message:=Message,PostType:=",ErrorLoggingTextFile")

try, CurrentURL := driver.url
Message = Trying to Grab URL of latest upload containing keyword: %VideoTitleLongWord%. Tab's current URL: %CurrentURL%
SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
; DevModeMsgBox(Message)

Loop, 4 {
	ElementIndexNumber := A_index - 1

	jsCheck = return document.getElementsByClassName('col')[%ElementIndexNumber%].outerHTML;
	try BrighteonURL := driver.executeScript(jsCheck)

	jsCheck = return document.getElementsByClassName('col')[%ElementIndexNumber%].textContent;
	try InnerText := driver.executeScript(jsCheck)

	if(InStr(InnerText, VideoTitleLongWord)){
		Message = Title Keyword was found on %A_index% loop, within element: %innerText%`nTrying to pull out BrighteonURL from element's outerHTML
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")

		BrighteonURL := StrSplit(BrighteonURL, "/dashboard/videos/")
		BrighteonURL := BrighteonURL[2]
		BrighteonURL := StrSplit(BrighteonURL, "><div")
		BrighteonURL := BrighteonURL[1]
		BrighteonURL := StrReplace(BrighteonURL, """", "")
		BrighteonURL := "https://www.brighteon.com/" . BrighteonURL
		Break
	}
	else, {
		message = Keyword was not within: %VideoTitle%. Trying again with next element.
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")

		BrighteonURL := 

	}

}


if(BrighteonURL = ""){
	Message = Upload Completed Successfully but failed to grab Share URL. Please Copy and Paste it in.
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	SaveDriverURLOFErrorPage()
	Return
}

Message = Upload Complete:`n%BrighteonURL%
SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")  
IniWrite, %BrighteonURL%, %VideoLinksIniFile%, URLs, BrighteonURL
SaveDriverURL()
AddToTotalVideosUploadedCount()

Return