LocalsUpload:
;------------------------------------------------
CurrentSite := "Locals"


SaveOrPostProgress(Message:="Navigating to Post Creation Page",PostType:="Tooltip,ErrorLoggingTextFile")
; SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile")

IniRead, LocalsPostPageURL, %SettingsIniFilepath%, General, LocalsPostPageURL, %A_Space%
if(LocalsPostPageURL = ""){
	Message = LocalsURL is blank.`nPlease add Locals URL to Settings.ini file under:`n`n[General]`nLocalsPostPageURL=
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	Return
}

if(InStr(LocalsPostPageURL, "/share/post")){
	LocalsPostPageURL := StrReplace(LocalsPostPageURL, "/share/post", "")
}

Status := NavigateFromBaseURLTo(LocalsPostPageURL)
if(Status)
Return


Message = Waiting for Page to fully load
SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile")
Xpath = //textarea[@id='body']
Status := Selenium_LoopToClickXpath(Xpath:=Xpath,NumOfLoops:=10,SleepLength:=1000)
if(Status){
	Message = Page did not load after 10 seconds. Force stopping refresh and trying to continue
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")

	send, {Escape} ; Temporary workaround, as Page seems to endlessly load for Stef

	Xpath = //textarea[@id='body']
	Status := Selenium_LoopToClickXpath(Xpath:=Xpath,NumOfLoops:=2,SleepLength:=1000)
	if(Status){
		SaveOrPostProgress(Message:="Post Failed: Check Login Status, or Website is Down",PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")

		Return
	}
}

TooltipThis("Inputting Title")
Loop, 5 { ; Attempt to input video description a couple of times


	if(A_index = 5){
		; Clipboard := VideoDescription
		Message = Failed to input Video Title
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")  
		Return
	}

	js = document.querySelector("#title").value = "%JSVideoTitle%";  ; Send content through javascript (Great for getting around emoji chrome limitaitons)
	try driver.executeScript(js)    ;Executes a Javascript on the webpage, mostly used for buttons.

	; msgbox 
	; try driver.findElementsByName("body").item[1].SendKeys(driver.Keys.SPACE)
	; driver.findElementsByID("ELEMENTID").item[1].SendKeys(driver.Keys.ENTER)
	; msgbox

	jsCheck = return document.querySelector("#title").value;  ; Send content through javascript (Great for getting around emoji chrome limitaitons)
	try VideoTitle := driver.executeScript(jsCheck)    ;Executes a Javascript on the webpage, mostly used for buttons.


	; try Description := driver.findElementsByName("body").item[1].Attribute("value") ;XPath: ID=site-title & span tag
	if(VideoTitle != "")
	Break
	sleep, 2000
}



; Input Video Description
; ------------------------------------------------
TooltipThis("Inputting Description")
Loop, 5 { 


	if(A_index = 5){
		Clipboard := VideoDescription
		Message = Unable to Input Video Description`nDescription copied to clipboard, please paste it in at your earliest convenience. 
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")  
		Return
	}

	js = document.getElementsByName('body')[0].value = "%JSVideoDescription%";  ; Send content through javascript (Great for getting around emoji chrome limitaitons)
	try driver.executeScript(js)    ;Executes a Javascript on the webpage, mostly used for buttons.

	try driver.findElementsByName("body").item[1].SendKeys(driver.Keys.SPACE)

	jsCheck = return document.getElementsByName('body')[0].value;  ; Send content through javascript (Great for getting around emoji chrome limitaitons)
	try Description := driver.executeScript(jsCheck)    ;Executes a Javascript on the webpage, mostly used for buttons.


	; try Description := driver.findElementsByName("body").item[1].Attribute("value") ;XPath: ID=site-title & span tag
	if(Description != "")
	Break
	sleep, 2000
}

; SaveOrPostProgress(Message:="Waiting Video to finish uploading",PostType:="Tooltip,ErrorLoggingTextFile")
Message = Uploading Video File
SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile")
Xpath = //div[@class='uploadvideo-wrapper']//input[@name='Filedata']
Status := Selenium_LoopToSendValueToXpath(Xpath:=Xpath,NumOfLoops:=2,SleepLength:=1000,StringTextContent:=VideoFilepath)
if(Status){
	Message = Failed to Upload Video
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	Return
}


; check if the "Auto Submit Post" checkbox is checked, and if not check it
js = return document.querySelector("#autosubmit_enabled").checked;
try AutoSubmitstatus := driver.executeScript(js)

if(AutoSubmitstatus = "0"){
	js = document.querySelector("li[id='autosubmit_container'] small").click() ; ; CHECK YES
	try driver.executeScript(js)    ; DevModeMsgBox(status)

	; double check that it got selected
	js = return document.querySelector("#autosubmit_enabled").checked;
	try AutoSubmitstatus := driver.executeScript(js)

	Message = AutoSubmitstatus after clicking checkbox: %AutoSubmitstatus%
	DevModeMsgBox(message)

	if(AutoSubmitstatus != "-1"){
		Message = Failed to check Auto-Submit Post checkbox
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
		SaveDriverURLOFErrorPage()
		Return
		; SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
	}
}


if(AutoSubmitstatus = "-1"){ ; if checked YES

	; check that there are no error messages
	js = return document.querySelector("div[class='form-error']").textContent; 
	try status := driver.executeScript(js)
	; DevModeMsgBox(status)
	if(status){ ;if element contains error text
		Message = Auto Publish failed: %status%
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
		SaveDriverURLOFErrorPage()
		Return
	}


	if(VideoThumbFilepath){
		Message = Uploading Thumbnail
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile")
		Xpath = //div[contains(@class,'post-video-attachments post-video-attachments_upd')]//div[contains(@class,'uploadfile-wrapper')]//input[contains(@name,'Filedata')]
		Status := Selenium_LoopToSendValueToXpath(Xpath:=Xpath,NumOfLoops:=2,SleepLength:=1000,StringTextContent:=VideoThumbFilepath)
		if(Status){
			Message = Failed to Attach Thumbnail
			SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
			Return
		}
	}

	; otherwise everything is good and we can move on to the next site and come back to grab the URL later
	; LocalsURL := "UploadedButNeedToGrabLink"
	; Return


	Message = Upload Started Successfully
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")

	LocalsURL := "LocalsUploadStartedNeedToGrabURL"
	; Msgbox % "LocalsURL: " LocalsURL
	IniWrite, %LocalsURL%, %VideoLinksIniFile%, URLs, LocalsURL
	AddToTotalVideosUploadedCount()

	; Set variable so that URL gets grabbed later in the upload
	LocalsGrabURL := 1

	Return
}
Return



;--------------\Locals----------------------------------










;--------------LocalsGrabURL----------------------------------
LocalsGrabURL:

CurrentSite := "Locals"
; msgbox, pause
SaveOrPostProgress(Message:="Navigating to Locals Feed to grab URL",PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")
; SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile")

IniRead, LocalsPostPageURL, %SettingsIniFilepath%, General, LocalsPostPageURL, %A_Space%
if(LocalsPostPageURL = ""){
	Message = LocalsURL is blank.`nPlease add Locals URL to Settings.ini file under:`n`n[General]`nLocalsPostPageURL=
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	Return
}

if(InStr(LocalsPostPageURL, "/share/post")){
	LocalsFeedPageURL := StrReplace(LocalsPostPageURL, "/share/post", "")
}


Status := ActivateChromeTab(LocalsPostPageURL)
if(Status = "Failed"){
	Message = Failed to Activate Locals Tab. Please grab URL manually
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	Return 
}


try currentpageURL := driver.url
if(InStr(currentpageURL,"share/post")){ ; we're still on create new post page
Message = Locals is still on the Create New Post page. Please double check if post was published successfully.
SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
SaveDriverURLOFErrorPage()
Return
}


; otherwise we should be on locals.com home feed page
; check for "Retrieve Draft button"
js = return document.querySelector("a[class='btn']").innerText; 
try, status := driver.executeScript(js)
if(status){
	Message = Video is in Draft Mode. Publishing.
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,DiscordErrorLogging")

	; video is in draft mode, we need to confirm the title and then publish it.

	; click Retrieve draft button
	js = document.querySelector("a[class='btn']").click()
	try, driver.executeScript(js)   

	js = return document.querySelector("#title").value
	try LocalsDraftTitle := driver.executeScript(JS) 

	if(LocalsDraftTitle != VideoTitle){
		Message = Failed to Grab URL. Locals Draft Title does not Match video Title:`nVideo Title: %VideoTitle%`nLocals Draft Title: %LocalsDraftTitle%
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
		SaveDriverURLOFErrorPage()
		Return
	}

	; otherwise we are good to publish video
	Xpath = (//button[@name='submitPost'])[1]
	Status := Selenium_LoopToClickXpath(Xpath:=Xpath,NumOfLoops:=2,SleepLength:=1000)
	if(Status){
		Message = Failed to click Publish button on saved Draft
		SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
		SaveDriverURLOFErrorPage()
		Return
	}

	sleep, 2000

}


/*
; Get word that's longer than 4 characters in video title
VideoTitleArray := StrSplit(VideoTitle, " ")
; Iterate from 1 to the end of the array:
Loop % VideoTitleArray.Length(){
	LongestWordInVideoTitle := VideoTitleArray[A_Index]
	LongestWordInVideoTitle := StrReplace(LongestWordInVideoTitle, "_","-")
	if(StrLen(LongestWordInVideoTitle) > 4)
	Break
}


*/


; get longest word in video title to use for grabbing the share link from the raw page
RegExMatch(VideoTitle, "ms)\b\S+(?CFindLongestWordInString)\b(?R)", m)
LongestWordInVideoTitle := longestWord
Msgbox % "LongestWordInVideoTitle: " LongestWordInVideoTitle

; MsgBox, Longest word: %longestWord%`, #%wordLength%




; Grab Video Share Link From Page Source
; ------------------------------------------------
; Iterate over the last couple of posts, find the post with the title that contains the Longest word from the uploaded video
; And grab the share URL for it

Message = Looking for - %LongestWordInVideoTitle% - within first 7 posts in order to grab share URL
SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")

loop, 7 {
	ElementIndexNum := A_index - 1
	Message = ElementIndexNum: %ElementIndexNum%
	DevModeMsgBox(Message)

	jscheck = return document.getElementsByClassName('post-bottom')[%ElementIndexNum%].outerHTML;
	try outerHTML := driver.executeScript(jsCheck)

	; clipboard := outerHTML
	; Msgbox % "outerHTML: " outerHTML

	if(DevMode){
		Message = Looking for LongestWordInVideoTitle: %LongestWordInVideoTitle% `nwithin outerHTML: %outerHTML%
		DevModeMsgBox(message)
		Clipboard := message
		; DevModeMsgBox(outerHTML)
	}



	if(InStr(OuterHTML,LongestWordInVideoTitle)){

		; @todo replace with regex
		Message = %LongestWordInVideoTitle% is in`n`n %OuterHTML%
		DevModeMsgBox(Message)

		Message = Found at at index: %A_index%
		DevModeMsgBox(message)
		; MsgBox, found match at %A_index%


		DevModeMsgBox("Pulling out url from outerhtml")

		ShareLink := StrSplit(OuterHTML, "data-url=")
		ShareLink := ShareLink[2]

		DevModeMsgBox(ShareLink)
		; Msgbox % "ShareLink: " ShareLink

		URLEndString = ">
		ShareLink := StrSplit(ShareLink, URLEndString)
		ShareLink := ShareLink[1]
		DevModeMsgBox(ShareLink)

		QuotationMark = "
		ShareLink := StrReplace(ShareLink,QuotationMark, "")
		DevModeMsgBox(ShareLink)
		Break
	}

	ShareLink :=
}

if(ShareLink = ""){
	Message = Video was published succsessfully, but failed to grab Share Link.
	SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging")
	SaveDriverURLOFErrorPage()
	Return
}


Message = Upload Complete: %ShareLink%
SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging")

DevModeMsgBox(ShareLink)
IniWrite, %ShareLink%, %VideoLinksIniFile%, URLs, LocalsURL
AddToTotalVideosUploadedCount()

SaveDriverURL()


Return
;--------------/LocalsGrabURL----------------------------------





