Import-Module PSWriteColor

#Set-Location 'F:\Library\Graphic Novels' #Resets location to root
#Set-Location 'E:\Comic'
#$txtDelete = 'F:\Library\Delete.txt'

function removeEmptyDirectory{
	remove-emtpy.ps1 -Path .\ -Remove -VerifyNoEmpty
}

function renamePages{
    # Parameter help description
    param (
        [string]$dirLocation,
        [int]$issuePart
    )

    Set-Location $dirLocation #Set location to the issue directory
    $files = Get-ChildItem * -Include '*.jpg', '*.png', '*.jpeg', '*.gif'
    
    for($i = 1; $i -le $files.Count; $i++){ #creates a serialized array of the new file names
        $newName = ([string]$issuePart).PadLeft(4,'0') + ([string]$i).PadLeft(4,'0') + $files[$i-1].Extension
        #$newName
        Rename-Item $files[$i-1] -NewName $newName 
    }
}

function unzipCBZ{
    param (
        $cbzFiles
    )

    $removeEmptyDirectoryDef = $Function:removeEmptyDirectory.ToString()
    $renamePagesDef = $Function:renamePages.ToString()

	$cbzFiles | ForEach-Object -parallel { #Creates a list of CBZ files on all the subdirectories and runs for each one
        #define functions inside the thrad
        $Function:removeEmptyDirectory = $using:removeEmptyDirectoryDef
        $Function:renamePages = $using:renamePagesDef
        
        Set-Location $_.DirectoryName #Changes location to a children directory to avoid uncompressing into the wrong folders
		7z x $_ -o* > $txtDelete 
        Remove-Item $_.FullName #Removes the CBZ file after extracted 
        Set-Location $_.BaseName #Set the location to the uncompressed directory
        $issueDirectoryLocation = Get-Location #store the issue location for later use

        #Remove emtpy directories and creates a check variable
        removeEmptyDirectory 
        $dirDirectories = Get-ChildItem -Directory

        #If statements to check and rename files according to how many directories they contain
        if (($dirDirectories).Count -gt 0){ 
            for ($i = 0; $i -le ($dirDirectories).Count; $i++){ #system to rename every file according with an increment of which "part" directory of the TPB they belong to
                renamePages $dirDirectories[$i] $i 
            }
            Set-Location $issueDirectoryLocation
            Get-ChildItem -Recurse -File -Exclude 'ComicInfo.xml' | Move-Item  -Destination $issueDirectoryLocation #move files to the root
            removeEmptyDirectory
            if ((Get-ChildItem -Directory).Count -gt 0){
                Get-ChildItem -Recurse -File 'ComicInfo.xml' | Remove-Item
                Set-Location $issueDirectoryLocation
                removeEmptyDirectory
            }
        }
        elseif (($dirDirectories).Count -eq 0){
            $dirLocation = Get-Location
            renamePages $dirLocation 0
        }
	} -ThrottleLimit 15
}

function convertFiles{
    Get-ChildItem -Recurse *.jpg | ForEach-Object -parallel { #convert PNG
        Set-Location $_.Directory
        $fileName = $_.BaseName
        magick convert -quality 100 $_ "$fileName.png"
        Remove-Item $_
    } 
    Get-ChildItem -Recurse *.png | ForEach-Object -parallel { #convert JPG
        Set-Location $_.Directory
        $fileName = $_.BaseName
        magick convert -quality 100 $_ "$fileName.jpg"
        Remove-Item $_
    }
}

function partDirs{
    param (
        $workingDir
    )
    $dirParts = Get-ChildItem -Directory -Recurse | Where-Object {$_.Name -match 'Part'}
    foreach ($dirPart in $dirParts){
        Set-Location $dirPart.Parent
        $TPBname = $dirPart.Name.Split(' (')
        if(!(Test-Path $TPBname[0])){
            New-Item -ItemType Directory $TPBname[0]
        }
        else{
            $nameFixed = $TPBname[0] + ' '
            $nameFixed
            $dirMove = Get-ChildItem -Directory -Exclude $TPBname[0] | Where-Object {$_.Name -match $nameFixed}
            if ($dirMove){
                $dirMove
                $TPBname[0]
                Move-Item $dirMove -Destination $TPBname[0]
            } 
        }
    }
    Set-Location $workingDir ################FIX THIS############
    #########################
    ############
    foreach ($dir in Get-ChildItem -Recurse -Directory){
        if(test-path($dir)){Set-Location $dir}
        
        $issueDirectoryLocation = Get-Location
        if(Get-ChildItem -Directory | Where-Object {$_.Name -match 'Part'}){
            $dirRename = Get-ChildItem -Directory
            for ($i = 0; $i -le ($dirRename).Count; $i++){ #system to rename every file according with an increment of which "part" directory of the TPB they belong to
                renamePages $dirRename[$i] $i
            }
            Set-Location $issueDirectoryLocation
            Get-ChildItem -Recurse -File -Exclude 'ComicInfo.xml' | Move-Item  -Destination $issueDirectoryLocation #move files to the root
            removeEmptyDirectory
        }
    }
}
switch ($args[0]) {
    '1'{
        $cbzFiles = Get-ChildItem *.cbz -Recurse -File
        unzipCBZ $cbzFiles
    }
    '2'{
        convertFiles
    }
    '3'{
        Set-Location $args[1]
        partDirs $args[1]
    }
    '4'{
        Set-Location 'F:\Library\Comic'
        foreach ($dir in Get-ChildItem -Recurse -Directory){
            renamePages $dir 0
        }
    }
}