#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#include <MsgBoxConstants.au3>
#include <Array.au3>
#include <File.au3>
#include <String.au3>
#include <InetConstants.au3>
#include <ProgressConstants.au3>
#include <GuiStatusBar.au3>

; Set default folder paths
Global Const $gShowID = True ; Toggle for showing or hiding the movie ID
Global Const $gDefaultFolderPaths[2] = ["H:\Selmane\NEW2", "G:\Selmane\NEW2"]

Func _SetDefaultFolderPath()
    ; Return the first existing default folder path
    For $sPath In $gDefaultFolderPaths
        If FileExists($sPath) Then Return $sPath
    Next
    Return ""
EndFunc

; Create resizable GUI
$Form = GUICreate("YTS Movie Cover Downloader v1.0", 800, 600, -1, -1, BitOR($GUI_SS_DEFAULT_GUI, $WS_SIZEBOX, $WS_MAXIMIZEBOX))

; Input controls
GUICtrlCreateLabel("Folder Path:", 10, 10, 70, 20)
$Input_Path = GUICtrlCreateInput(_SetDefaultFolderPath(), 90, 10, 580, 20)
$Browse = GUICtrlCreateButton("Browse", 680, 10, 70, 20)

; Range controls
GUICtrlCreateGroup("Processing Range", 10, 40, 740, 60)
GUICtrlCreateLabel("Start at:", 20, 60, 50, 20)
$InputStart = GUICtrlCreateInput("1", 70, 60, 60, 20, BitOR($ES_NUMBER, $ES_RIGHT))
GUICtrlCreateUpdown($InputStart)
GUICtrlCreateLabel("End at:", 150, 60, 50, 20)
$InputEnd = GUICtrlCreateInput("0", 200, 60, 60, 20, BitOR($ES_NUMBER, $ES_RIGHT))
GUICtrlCreateUpdown($InputEnd)
GUICtrlCreateLabel("(0 = process until end)", 270, 60, 120, 20)
$Start = GUICtrlCreateButton("Start Download", 650, 55, 90, 30)
GUICtrlCreateGroup("", -99, -99, 1, 1)

; Status Group
GUICtrlCreateGroup("Status", 10, 110, 780, 150)
GUICtrlCreateLabel("Progress:", 20, 130, 60, 20)
$ProgressBar = GUICtrlCreateProgress(90, 130, 690, 20)
GUICtrlCreateLabel("Current Movie:", 20, 160, 80, 20)
$CurrentMovie = GUICtrlCreateLabel("", 110, 160, 670, 20)
GUICtrlCreateLabel("Operation:", 20, 190, 80, 20)
$CurrentOperation = GUICtrlCreateLabel("", 110, 190, 670, 20)
GUICtrlCreateLabel("URL:", 20, 220, 80, 20)
$CurrentURL = GUICtrlCreateLabel("", 110, 220, 670, 20)
GUICtrlCreateGroup("", -99, -99, 1, 1)

; Log area
GUICtrlCreateLabel("Log:", 10, 270, 30, 20)
$Progress = GUICtrlCreateEdit("", 10, 290, 780, 300, BitOR($ES_MULTILINE, $ES_READONLY, $WS_VSCROLL, $ES_AUTOVSCROLL))

; Status bar
$StatusBar = _GUICtrlStatusBar_Create($Form)
Local $aStatusBarParts[4] = [150, 300, 500, -1]
_GUICtrlStatusBar_SetParts($StatusBar, $aStatusBarParts)
GUICtrlSetResizing($StatusBar, $GUI_DOCKBOTTOM)

GUISetState(@SW_SHOW)

; Global variables
Global $aFolderList[0]
Global $aFolderPaths[0]
Global $iCurrentIndex = 0

Func _UpdateStatus($sMovie = "", $sOperation = "", $sURL = "")
    ; Update GUI controls with current status information
    If $sMovie <> "" Then GUICtrlSetData($CurrentMovie, $sMovie)
    If $sOperation <> "" Then GUICtrlSetData($CurrentOperation, $sOperation)
    If $sURL <> "" Then GUICtrlSetData($CurrentURL, $sURL)

    If UBound($aFolderList) > 0 Then
        Local $iPercent = Round(($iCurrentIndex * 100) / UBound($aFolderList))
        GUICtrlSetData($ProgressBar, $iPercent)
        _GUICtrlStatusBar_SetText($StatusBar, "Progress: " & $iCurrentIndex & "/" & UBound($aFolderList), 0)
        _GUICtrlStatusBar_SetText($StatusBar, "Movie: " & StringLeft($sMovie, 20), 1)
        _GUICtrlStatusBar_SetText($StatusBar, $sOperation, 2)
        GUICtrlSetData($StatusBar, "Range: " & GUICtrlRead($InputStart) & "-" & GUICtrlRead($InputEnd), 3)
    EndIf
EndFunc

Func _GetFolderList($sPath)
    _LogMessage("Getting folder list...")
    _UpdateStatus("", "Scanning folders...", "")

    Local $aFolders = _FileListToArray($sPath, "*", $FLTA_FOLDERS)
    If @error Then Return

    For $i = 1 To $aFolders[0]
        If StringRegExp($aFolders[$i], "\(\d{4}\)") Then
            _ArrayAdd($aFolderList, $aFolders[$i])
            _ArrayAdd($aFolderPaths, $sPath & "\" & $aFolders[$i])
            _LogMessage("Found: " & $aFolders[$i])
        EndIf
    Next

    _LogMessage("Total folders found: " & UBound($aFolderList))
    GUICtrlSetData($ProgressBar, 0)

    ; Update End input if it's 0
    If GUICtrlRead($InputEnd) = "0" Then GUICtrlSetData($InputEnd, UBound($aFolderList))
EndFunc

Func _DownloadCover($sMovieName, $sPath)
    ; Extract movie title and year
    Local $aMatches = StringRegExp($sMovieName, "(.*?)\s*[\(\[]?(\d{4})[\)\]]?", 3)
    If @error Or UBound($aMatches) <> 2 Then
        _LogMessage("❌ [Error] Could not extract movie title and year", "Red")
        Return
    EndIf

    Local $sTitle = _StringToURL($aMatches[0])
    Local $sYear = $aMatches[1]
    Local $sFinalName = $sTitle & "_" & $sYear

    ; Prepare log message with ID toggle
    Local $sLogMovieID = $gShowID ? " [" & $sMovieName & "]" : ""

    ; Check if file already exists
    Local $sOutputFile = $sPath & "\" & $sFinalName & ".jpg"
    If FileExists($sOutputFile) Then
        _LogMessage("✅ [Cover already exists]" & $sLogMovieID, "Green")
        Return
    EndIf

    ; Try to download cover
    Local $sLargeCover = "https://img.yts.mx/assets/images/movies/" & $sFinalName & "/large-cover.jpg"
    Local $sMediumCover = "https://img.yts.mx/assets/images/movies/" & $sFinalName & "/medium-cover.jpg"

    ; Log the URL being used
    _LogMessage("Downloading cover from: " & $sLargeCover, "Blue")

    ; Use InetGet to download the image
    Local $hDownload = InetGet($sLargeCover, $sOutputFile, 1)
    If @error Then
        ; Fallback to medium cover if large fails
        _LogMessage("❌ [Failed to download large cover, trying medium...]", "Red")
        $hDownload = InetGet($sMediumCover, $sOutputFile, 1)
        If @error Then
            _LogMessage("❌ [Failed to download medium cover]", "Red")
            Return
        EndIf
    EndIf

    _LogMessage("✅ [Cover downloaded successfully]" & $sLogMovieID, "Green")
EndFunc

Func _StringToURL($sString)
    ; Clean and format the title for the URL
    Local $sCleanTitle = StringRegExpReplace($sString, "[;'\-\:\,]", "")
    Return StringLower(StringReplace($sCleanTitle, " ", "_"))
EndFunc

Func _LogMessage($sMessage, $sColor = "Black")
    GUICtrlSetData($Progress, GUICtrlRead($Progress) & @CRLF & $sMessage)
EndFunc

; Main loop
While True
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
        Case $Start
            _GetFolderList(GUICtrlRead($Input_Path))
            For $i = GUICtrlRead($InputStart) To GUICtrlRead($InputEnd)
                $iCurrentIndex = $i
                _DownloadCover($aFolderList[$i - 1], $aFolderPaths[$i - 1])
                _UpdateStatus($aFolderList[$i - 1], "Downloading...", "")
            Next
            _LogMessage("All downloads completed!")
            _UpdateStatus("", "Finished", "")
        Case $Browse
            Local $sNewFolderPath = FileSelectFolder("Select folder", "")
            If @error Then ContinueLoop
            GUICtrlSetData($Input_Path, $sNewFolderPath)
    EndSwitch
WEnd

-------------------
; Status bar is not sticing too the buttom when the window resized