;---ENVIRONMENT---------------------------------------------------------------------
#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
;#Warn  ; Enable warnings to assist with detecting common errors.
;DetectHiddenWindows, On
#SingleInstance, Force
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
;SetKeyDelay, 500
CoordMode, ToolTip, Screen
CoordMode, Mouse, Screen
;#NoTrayIcon


; Menu, Tray, Icon, %A_scriptDir%\Assets\LBRY-Process-Killer.ico

;---Notes/Extra Info/#Includes------------------------------------------------------


;---VARIABLES-----------------------------------------------------------------------
global DiscordWebhookBotURL

PassedParameter = %1%
if(PassedParameter = "Kill")
ExitApp

IniRead, DiscordWebhookBotURL, %A_scriptDir%\..\Settings.ini, General, DiscordWebhookBotURL, %A_Space%
if(DiscordWebhookBotURL = ""){
    ; msgbox, Unable to Read Settings.ini for DiscordWebhookBotURL.`nProgram will not be able to post seed status to Discord
    ; ExitApp
}


;---MAIN SCRIPT---------------------------------------------------------------------
lbrynetlog_FP = C:\Users\%A_Username%\AppData\Local\lbry\lbrynet\lbrynet.log
if(!FileExist(lbrynetlog_FP)){
    Message = lbrynet.log not found in the usual location. `nPlease submit issue on gitea to add functionality for custom locations.`nClick OK to open gitea page.
    msgbox % Message
    run, https://git.zinchuk.xyz/yuriy/LBRY-Process-Killer
    ExitApp
}


FileRead, lbrynetlogContents, C:\Users\%A_Username%\AppData\Local\lbry\lbrynet\lbrynet.log
if(lbrynetlogContents = ""){
    Message = LBRYNet.log exists at normal location, but is currently empty. `nPlease submit issue on gitea about this error message `nClick OK to open gitea page and exit.
    msgbox % Message
    run, https://git.zinchuk.xyz/yuriy/LBRY-Process-Killer
    ExitApp
}

; Msgbox % "lbrynetlogContents: " lbrynetlogContents

LogContentsArray := StrSplit(lbrynetlogContents, "`n")
OriginalArrayLenght := LogContentsArray.Length()   ; Save total number of items in the array

Loop, 45 { ; 3.75 hours, if not complete by this time then exit
    sleep, 300000 ; 5 minutes
    ; sleep, 60000
    if(A_index = 6 OR A_index = 12 OR A_index = 24 OR A_index = 36 OR A_index = 48){ ; 30, 60, 120 minutes
        Message = LBRY: Still waiting for Video to finish Uploading to Reflectors
        PostProgressToDiscord(Message)
    }

    FileRead, lbrynetlogContents, C:\Users\%A_username%\AppData\Local\lbry\lbrynet\lbrynet.log
    UpdatedLogContentsArray := StrSplit(lbrynetlogContents, "`n") 
    ArrayLenght := UpdatedLogContentsArray.Length()   ; Count number of individual rows

    Loop, %ArrayLenght% { 
        if(A_index < %OriginalArrayLenght%)
        Continue ;  Skip all lines that that were present in the original .log

        CurrentLineContents := UpdatedLogContentsArray[A_index]

        if(InStr(CurrentLineContents, "Finished sending reflector")){ ; Upload Complete Text on lbrylog
            SeedingComplete := 1 ; mark seeding as complete and go to next loop
            OriginalArrayLenght := A_index ; set variable to equal this loop number. So all lines up to this one get skipped next loop round
            Continue
        }

        if(InStr(CurrentLineContents, "Sent reflector blob")){ ; Means "Still Uploading" in LBRY API
        SeedingComplete := 0 ; mark seeding as incomplete as there is still an upload in progress
        Continue
    }
}



if(SeedingComplete){
    Process, Close, LBRY.exe ; terminate LBRY if it's running

    if(DiscordWebhookBotURL){
        Message = LBRY: Video Finished Seeding to Reflectors. LBRY Process Killed.
        PostProgressToDiscord(Message)
    }

    ExitApp
}


}



;---FUNCTIONS-----------------------------------------------------------------------



PostProgressToDiscord(Message){
    ; Need to transform the message into a json string: 
    FormatTime, CurrentTime, YYYYMMDDHH24MISS, hh:mm 
    ; Message := "-----------" . CurrentTime . "-----------" . "`n" . Message ; add a ------- to the top of the message to help split them up visually on discord

    ; Escape Backslashes
    Message := StrReplace(Message, "", "\/")

    ; Escape quotation marks 
    SingleQuotationmark = "
    ReplacedQuote = \"
    Message := StrReplace(Message, SingleQuotationmark, ReplacedQuote)

    ; Escape New Character 
    Message := StrReplace(Message, "`n", "\n")

    ; Convert into json string
    JsonString=
    (
    {
      "content": "%Message%"
  }
  )
    try WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1")
    try WebRequest.Open("POST", DiscordWebhookBotURL, false)
    try WebRequest.SetRequestHeader("Content-Type", "application/json")
    try WebRequest.Send(JsonString)  
}