$Script:Version = "H-Cleaner v1.0.1"
#Ersteller: Florian Späth
#Diese Software soll helfen im H-Laufwerk geordnet Daten zu verschieben und löschen.

##
### Notiz: Ticket #66 geschlossen, Ticket #51 geschlossen
##

#### Pseudonymisierung und Log ####
#. .\pseudonymisierung.ps1
#Log "### Tool gestartet ###" -clear
$Global:Log=$false
####

Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Windows.Forms
[System.Reflection.Assembly]::LoadWithPartialName('System.Drawing')  | Out-Null

#### Lädt Scripte ####

. .\GUIS\del\del.ps1
. .\GUIS\delconf\delconf.ps1
. .\GUIS\filter\filter.ps1
. .\GUIS\info\info.ps1
. .\GUIS\main\main.ps1
. .\GUIS\scanner\scanner.ps1

#### Ordner die bei der Suche ausgeschlossen werden ####

$Script:exclude=@("H:\EINSTELLUNGEN","H:\Application Data","H:\meancore","H:\Cleaner","H:\Microsoft")

#### Lädt Guis ####
$Script:main = Load_main $PSScriptRoot          # Variable: $main
$Script:scanner = Load_scanner $PSScriptRoot       # Variable: $scanner
$Script:filter = Load_filter $PSScriptRoot        # Variable: $filter
$Script:del = Load_del $PSScriptRoot           # Variable: $del
$Script:delconf = Load_delconf $PSScriptRoot       # Variable: $delconf
$Script:info = Load_info $PSScriptRoot          # Variable: $info

#### Definition globaler Variablen ####

$Script:ScriptRoot = $PSScriptRoot
$Script:iconpath = "$PSScriptRoot\icons"

$Script:Elementcount = 0
$Script:Elementsize = 0

    ### Farb Variablen ###

    $Script:Standardbtncolor = "#00b8d4"
    $Script:Delcolor = "#d50000"
    $Script:BackgroundMovecolor = "#FFFFEB9C"
    $Script:ForegroundMovecolor = "#FF9C6500"
    $Script:Foregroundgrey = "#FF7A7A7A"
    $Script:Backgroundgrey = "#FFC5C5C5"

#### Verknüpfungen GUI Objekte - Variablen ####

    ### Info ###

    $infook = $info.findName("btnok")

    ### DelConf ###
    
    $delconfok = $delconf.FindName("btnok")

#### Funktionen ####
    ### Global ###
    function Load_Iconfile {
        $Script:types =New-Object int[][] (4)
        $Script:icontypes = @()
        $iconcsv = Import-Csv "$PSScriptRoot\icons.csv" -Encoding utf8
        for ($i = 0; $i -lt $iconcsv.Count; $i++) {
            $Script:icontypes += $iconcsv.Dateiendung[$i]
            for ($a = 0; $a -lt 3; $a++) {
                if ($iconcsv.Type[$i] -eq $a) {
                    $Script:types[$a] += $iconcsv.ID[$i] 
                }
                [System.Windows.Forms.Application]::DoEvents()
            }
            [System.Windows.Forms.Application]::DoEvents()
        }  
        Write-Host $Script:Types
    } 

    function calc_Size {
        param($number)
        $res = $number/1MB
        $size = " MB"
        if($res -gt 1024){
            $res = $number/1GB
            $size = " GB"
        }
        $res = $res.ToString(".00")
        if ($res.StartsWith(",") ) {
            $res = "0" + $res
        }
        return $res + $size
    }
 
    function Get_Freespace (){
        # 0=Text Auslastung; 1=Freier Speicher; 2=Gesamter Speicher; 3=Belegter Speicher; 4=Wert für ProgressBar; 5=OFFLINE
        $array=@("",0,0,0,$false)
        $use = Get-WMIObject Win32_LogicalDisk -filter "name='H:'"
        $check = Get-WMIObject Win32_LogicalDisk -filter "name='C:'"
        if ($use.size -ne $check.size) {
            $array[1] = calc_Size $use.Freespace
            $array[2] = calc_Size $use.size
            $free = calc_Size $use.Freespace
            $size = calc_Size $use.size
            $Script:used = $use.size-$use.Freespace
            $array[3] = calc_Size ($use.size-($use.size-$use.Freespace))
            if (!$use) {
                $array[0] = "                  FEHLER"
            }else {
                $array[0] = "$free frei von $size"
                $bar = ($use.Freespace/$use.size)*100
                $array[4] = 100-$bar
            }
        }else{
            $array[4] = 100
            $array[5] = $true
        }
        #$text = "Freespace: "+$array[1]+"; Used: "+$array[2] 
        #Log $text -clear
        Set_Defaults_Scanner $array
        Set_Defaults_Main $array
    }

    function count_element {
        param (
            $count, $size
        )
        if ($count) {
            $Script:Elementcount++
            $Script:Elementsize = $Script:Elementsize+$size
        }else {
            $Script:Elementcount--
            $Script:Elementsize = $Script:Elementsize-$size
        }
        if ($Script:Elementcount -eq 0) {
            $maindel.Background = $Script:Backgroundgrey
            $mainmove.Background = $Script:Backgroundgrey
            $maindel.Foreground = $Script:Foregroundgrey
            $mainmove.Foreground = $Script:Foregroundgrey
            $mainmove.IsEnabled=$false
            $maindel.IsEnabled=$false
            $Deldel.Background = $Script:Backgroundgrey
            $Deldel.Foreground = $Script:Foregroundgrey
            $Deldel.IsEnabled = $false

            $DelMove.Background = "$Script:Backgroundgrey"
            $DelMove.Foreground = "$Script:Foregroundgrey"
            $DelMove.IsEnabled = $false
        }else {
            $maindel.Background="$Script:Delcolor"
            $mainmove.Background="$Script:BackgroundMovecolor"
            $maindel.Foreground="white"
            $mainmove.Foreground="$Script:ForegroundMovecolor"
            $mainmove.IsEnabled=$true
            $maindel.IsEnabled=$true
            $Deldel.Background = "$Script:Delcolor"
            $Deldel.Foreground = "white"
            $Deldel.IsEnabled = $true

            $DelMove.Background = "$Script:BackgroundMovecolor"
            $DelMove.Foreground = "$Script:ForegroundMovecolor"
            $DelMove.IsEnabled = $true
        }
        $size = calc_Size $Script:Elementsize
        if ($Script:Elementcount -le 1) {
            $Delstats.Text = " $Script:Elementcount Element $size"
            $mainelements.Text = " $Script:Elementcount Element"
            $delconfelements.Text = " $Script:Elementcount Element"
        }else {
            $Delstats.Text = " $Script:Elementcount Elemente $size"
            $mainelements.Text = " $Script:Elementcount Elemente"
            $delconfelements.Text = " $Script:Elementcount Elemente"
        }
        $mainsize.Text = " $size"
        $delconfsize.Text = " $size"
    }

    ### GUIs ###
        ## Scanner ##

        $scannerscan.Add_Click({
            Start_Scan 
            (New-Object -ComObject WScript.Shell).AppActivate((Get-Process | Where-Object { $_.Id -Match $PID }).MainWindowTitle)
        })

        $scanner.Add_KeyDown{
            param(
                [Parameter(Mandatory)][Object]$sender,
                [Parameter(Mandatory)][Windows.Input.KeyEventArgs]$e
            )
            if($e.Key -eq "Enter"){
                Start_Scan
                (New-Object -ComObject WScript.Shell).AppActivate((Get-Process | Where-Object { $_.Id -Match $PID }).MainWindowTitle)
            }
        }

        ## Main ##

        $mainscanner.Add_Click({
            $main.Hide()
            $scanner.ShowDialog() | Out-Null
        })

        $mainfilter.Add_Click({
            $filter.Showdialog() | Out-Null
        })

        $maininfo.Add_Click({
            $info.ShowDialog() | Out-Null
        })

        $maintree.Add_KeyDown{
            param(
                [Parameter(Mandatory)][Object]$sender,
                [Parameter(Mandatory)][Windows.Input.KeyEventArgs]$e
            )
            if($e.Key -eq "Enter"){
                $maintree.SelectedItem.IsExpanded = $true
                    Browser_Path -path $maintree.SelectedItem.tag
            }
        }

        $maintree.Add_MouseLeftButtonUp({
            if ($maintree.SelectedItem.tag -ne $null) {
                $maintree.SelectedItem.IsExpanded = $true
                Browser_Path -path $maintree.SelectedItem.tag
                #if ($Script:sortmain[3]) {
                #    main_sortsize
                #}else{
                #    main_sortname
                #}
            }
        })

        $mainbrowser.Add_MouseLeftButtonUp({
            if ($mainbrowser.Selecteditems.tag -ne $null) {
                $logcontent = "Main: Clicked " + $mainbrowser.Selecteditems.tag
                #Log $logcontent -clear
                Check_Browser $mainbrowser.Selecteditems.tag
            }
        })

        $mainsortname.Add_MouseLeftButtonUp({
            if ($mainbrowser.Items.Count -ne 1) {
                #Log "### Sortierung nach Name ###" -clear
                main_sortname -change
            }
        })

        $mainsortsize.Add_MouseLeftButtonUp({
            if ($mainbrowser.Items.Count -ne 1) {
                #Log "### Sortierung nach Größe ###" -clear
                main_sortsize -change
            }
        })

        $maincheckall.Add_MouseLeftButtonUp({
            main_checkall
        })

        $mainswitch.Add_Click({
            if ($Script:filtercheck[4]) {
                #Log "### Filter ohne Unterordner ###" -clear
                $mainimgswitch.Source = "$ScriptRoot/Source/swfalse.png"
                $Script:filtercheck[4] = $false
                Browser_Path -path $maintree.SelectedItem.tag
            }else {
                #Log "### Filter mit Unterordner ###" -clear
                $mainimgswitch.Source = "$ScriptRoot/Source/swtrue.png"
                $Script:filtercheck[4] =$true
                Browser_Path -path $maintree.SelectedItem.tag
            }
            
        })

        $mainmove.Add_Click({
            $Script:movelocation = Select-FolderDialog
            if ($Script:movelocation -ne $false) {
                #Log "### Clicked MOVE Button ###" -clear
                Reset_Filter
                Browser_del
                $Script:Delwarning.Visibility = "Hidden"
                $Script:Movewarning.Visibility = "Visible"
                $Script:Movewarning.Content = "Zielverzeichnis: $Script:movelocation "
    
                $Script:Movemarked.Visibility = "Visible"
                $Script:Delmarked.Visibility = "Hidden"
    
                $Deldel.Visibility="Hidden"
                $DelMove.Visibility="Visible"

                $Script:Deltb.Visibility = "Hidden"
                $Script:movetb.Visibility = "Visible"
                $Script:whattodo="move"
                $main.Hide()
                $Del.ShowDialog() | Out-Null
            }
        })

        $maindel.Add_Click({
            #Log "### Clicked DEL Button ###" -clear
            Reset_Filter
            Browser_del
            $Script:Delwarning.Visibility = "Visible"
            $Script:Movewarning.Visibility = "Hidden"

            $Script:Delmarked.Visibility = "Visible"
            $Script:Movemarked.Visibility = "Hidden"
    
            $Deldel.Visibility="Visible"
            $DelMove.Visibility="Hidden"

            $Deldel.Background = "$Script:Delcolor"
            $Deldel.Foreground = "white"
            $Script:Deltb.Visibility = "Visible"
            $Script:movetb.Visibility = "Hidden"
            $Script:whattodo="delete"
            $main.Hide()
            $Del.ShowDialog() | Out-Null
        })

        ## Del ##

        $Script:Delback.Add_Click({
            Browser_Path -path $maintree.SelectedItem.tag
            $Del.Hide()
            $main.ShowDialog() | Out-Null
        })

        $Script:Deldel.Add_Click({
            final_action
            Get_TreeView
            Browser_Path -path $maintree.SelectedItem.tag
            $del.hide()
            $delconf.ShowDialog() | Out-Null
        })

        $Script:DelMove.Add_Click({
            final_action
            Get_TreeView
            Browser_Path -path $maintree.SelectedItem.tag
            $del.hide()
            $delconf.ShowDialog() | Out-Null
        })

        $delbrowser.Add_MouseLeftButtonUp({
            if ($delbrowser.Selecteditems.tag -ne $null) {
                $logcontent = "Del: Clicked " + $delbrowser.Selecteditems.tag
                #Log $logcontent -clear
                Check_Del $delbrowser.Selecteditems.tag
            }
        })

        $Delsortname.Add_MouseLeftButtonUp({
            del_sortname
        })

        $Delsortsize.Add_MouseLeftButtonUp({
            del_sortsize
        })

        $Delcheckall.Add_MouseLeftButtonUp({
            del_checkall
        })

        ## Filter ##

        $script:filterok.Add_Click({
            $filter.Hide()
            Update_Filter
            $check=$false
            foreach($item in $Script:filtercheck){
                if ($item) {
                    $check=$true
                }
                [System.Windows.Forms.Application]::DoEvents()
            }
            if ($check) {
                Filter_data -tag $maintree.SelectedItem.tag
            }else {
                Browser_Path -path $maintree.SelectedItem.tag
            }
        })

        $Script:filterreset.Add_Click({
            Reset_Filter
            Update_Filter
            Browser_Path -path $maintree.SelectedItem.tag
            $filter.Hide()
        })

        $filter.Add_MouseLeftButtonDown({
            $filter.DragMove()
        })

        $filteroffice.Add_Click({
            if ($Script:filtercheck[0]) {
                $Filteroffice.background = "#444444"
                $Script:filtercheck[0] = $false
            }else {
                $Filteroffice.background = "#00c853"
                $Script:filtercheck[0] = $true
            }
            Update_Filter
        })

        $filterbilder.Add_Click({
            if ($Script:filtercheck[1]) {
                $Filterbilder.background = "#444444"
                $Script:filtercheck[1] = $false
            }else {
                $Filterbilder.background = "#00c853"
                $Script:filtercheck[1] = $true
            }
            Update_Filter
        })

        $filtervideos.Add_Click({
            if ($Script:filtercheck[2]) {
                $Filtervideos.background = "#444444"
                $Script:filtercheck[2] = $false
            }else {
                $Filtervideos.background = "#00c853"
                $Script:filtercheck[2] = $true
            }
            Update_Filter
        })

        $filteraudios.Add_Click({
            if ($Script:filtercheck[3]) {
                $Filteraudios.background = "#444444"
                $Script:filtercheck[3] = $false
            }else {
                $Filteraudios.background = "#00c853"
                $Script:filtercheck[3] = $true
            }
            Update_Filter
        })

        ## Info ##

        $info.Add_MouseLeftButtonDown({
            $info.DragMove()
        })
        
        $infook.Add_Click({
            $info.Hide()
        })

        ## DelConf ##

        $delconf.Add_MouseLeftButtonDown({
            $delconf.DragMove()
        })

        $delconfok.Add_Click({
            $delconf.Hide()
            $Script:Elementcount = 1
            $Script:Elementsize = 0
            count_element $false 0
            $maintree.Items[0].IsExpanded = $true
            $maintree.Items[0].IsSelected = $true
            $main.ShowDialog() | Out-Null
        })

#### Startet die Anwendung ####

    ### Initialisieren ###
    Get_Freespace
    Load_Iconfile 

    ### Öffnet erstes Fenster ### 

    #Log "### Cleaner sichtbar ###" -clear

    $Scanner.ShowDialog() | Out-Null

    #Add-Content -Path .\Log.txt -Value $Script:logvar