##Create work folders
#New-Item "C:\Users\$env:username\downloads\checkudvej1" -type Directory -Force
#New-Item "C:\Users\$env:username\downloads\checkudvej2" -type Directory -Force
#New-Item "C:\Users\$env:username\Documents\logs" -type Directory -Force
#New-Item "C:\Users\$env:username\downloads\mailfile" -type Directory -Force
#
##Create Mail work Folder (remember to create a rule to sort checkudvej mails into that folder)
#$olApp = new-object -comobject outlook.application
#$namespace = $olApp.GetNamespace("MAPI")
## Get Inbox
#$Folder = $namespace.GetDefaultFolder(6)
#
#$MatchCheckudvejmailfolder = $inbox.Folders | Where-Object  { $_.FolderPath -match 'Checkudvej' } 
#
#if ($MatchCheckudvejmailfolder) {
#  Write-Output "Folder $MatchCheckudvejmailfolder exists."
#} else {
#  Write-Output "Folder $MatchCheckudvejmailfolder does not exist."
#  $Folder.Parent.folders.Add("Checkudvej") 
#}
#
## End Inbox 
#$olApp.Quit | Out-Null
#[GC]::Collect()


#Grab email from user
#$Useremail = Read-Host -Prompt 'Input your Email'

# link to the folder 
#$olFolderPath = "\\$Useremail\Inbox\Checkudvej"
# link to the folder 
$olFolderPath = "\\alexander.warme@urbanandmainlines.com\Inbox\Checkudvej"

# set the location to temporary file
$filePath = "C:\Users\$env:username\Downloads\mailfile"
# use MAPI name space
$outlook = new-object -com outlook.application; 
$mapi = $outlook.GetNameSpace("MAPI");
# set the Inbox folder id
$olDefaultFolderInbox = 6
$inbox = $mapi.GetDefaultFolder($olDefaultFolderInbox) 
# access the target subfolder
$olTargetFolder = $inbox.Folders | Where-Object { $_.FolderPath -eq $olFolderPath }
# load emails
$emails = $olTargetFolder.Items
# process the emails 

foreach ($email in $emails)  {
    
# format the timestamp
# $timestamp = $email.ReceivedTime.ToString("yyyyMMddhhmmss")
# filter out the attachments
    foreach ($attachment in $email.Attachments) {
        if ($attachment.FileName -like "*.xlsx"){
            # insert the timestamp into the file name
            $fileName = $attachment.FileName
            #$fileName = $fileName.Insert($fileName.IndexOf('.'),$timestamp)
            # save the attachment
            $attachment.saveasfile((Join-Path $filePath $fileName)) 
        } 
    } 
}

Get-ChildItem C:\Users\$env:username\Downloads\mailfile -Recurse -Filter 'checkudvej1*'  | Move-Item -Force -Destination "C:\Users\$env:username\Downloads\checkudvej1\" 
Get-ChildItem C:\Users\$env:username\Downloads\mailfile -Recurse -Filter 'checkudvej2*' | Move-Item -Force -Destination "C:\Users\$env:username\Downloads\checkudvej2\" 

 #choose checkudvej 1 or 2
 
 $CHK1 = New-Object System.Management.Automation.Host.ChoiceDescription '&Checkudvej1', 'Checkudvej 1'
 $CHK2 = New-Object System.Management.Automation.Host.ChoiceDescription '&Checkudvej2', 'Checkudvej 2'

 $options = [System.Management.Automation.Host.ChoiceDescription[]]($CHK1, $CHK2)
 $title = 'Choose Checkudvej File'
 $message = "Choose the Checkudvej file of the day"
 $result = $host.ui.PromptForChoice($title, $message, $options, 0)
 if ($result -eq 0) {
     $choice = "Checkudvej 1"
     $todayxlsfiles=(Get-ChildItem -Path C:\Users\$env:username\Downloads\checkudvej1\ -Filter 'checkudvej1*' | Select-Object -ExpandProperty FullName )
 }
 elseif ($result -eq 1) {
     $choice = "Checkudvej 2"
     $todayxlsfiles=(Get-ChildItem -Path C:\Users\$env:username\Downloads\checkudvej2\ -Filter 'checkudvej2*' | Select-Object -ExpandProperty FullName )
  
 }

 else {
     $choice = "Try again"
 }
 "Du har Valgt: {0}" -f $choice

($superfilepath=$todayxlsfiles)

#check superfilepath
#$superfilepath.ToLower()

#grab pw
#set lowercase
$superlower=$superfilepath.ToLower()

#match end
$superlower -match '(?<=_)(.*?)(?=\.)' | Out-Null
#test match value
#$Matches[0]
#set pw on match
$password=$Matches[0] 
#test pw
#Write-Host "Matched password"
#$password
#grab name for save
$filesavename=[System.IO.Path]::GetFileNameWithoutExtension($todayxlsfiles) 

#open excel
$excel               = New-Object -ComObject Excel.Application
$excel.Visible       = $False
$excel.DisplayAlerts = $False

#open with saved password
($wb    = $excel.Workbooks.Open($superfilepath,0,0,5,$password)) | Out-Null


#createSaveDirectory
$Dirsave=Get-ChildItem -Directory $superfilepath
                                                                                                                         

#combine dir and filename and save excel
$wb.SaveAs($Dirsave.DirectoryName+'\'+$filesavename,6,'') 
                   
#Close Excel
$excel.Quit() | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
Remove-Variable excel


#create config entry
$nameconfig=$filesavename+".csv"

#move csv files
Get-Childitem -Recurse C:\Users\$env:username\Downloads\checkudvej1\ -Filter 'checkudvej*.csv' | Move-Item -Force -Destination "\\p-replacement\PurseCorrection\" 
Get-Childitem -Recurse C:\Users\$env:username\Downloads\checkudvej2\ -Filter 'checkudvej*.csv' | Move-Item -Force -Destination "\\p-replacement\PurseCorrection\" 

#grab config
$content = Get-Content "\\p-replacement\PurseCorrection\PurseCorrectionConsole.exe.config"
#match line 22
$content[22]

#change line 22 key
$content[22] = $content[22] -replace "value=.*", ('value="'+$nameconfig +'"/>')
$content | Set-Content \\p-replacement\PurseCorrection\PurseCorrectionConsole.exe.config

#cleanup
Get-Childitem -Recurse C:\Users\$env:username\Downloads\checkudvej1\ -Filter 'checkudvej*.xlsx' | Remove-Item -Force 
Get-Childitem -Recurse C:\Users\$env:username\Downloads\checkudvej2\ -Filter 'checkudvej*.xlsx' | Remove-Item -Force 

write-host "Now run AHK Script Checkudvej.AHK in C:\PurseCorrection\"
Start-Process "$env:windir\system32\mstsc.exe" -ArgumentList "/v:p-replacement"


#wait for log to be 1000kb
while ($true) {
  $logfilematch=Get-ChildItem -Path '\\p-replacement\PurseCorrection\logs\' -Filter "$filesavename*" | Where-Object {$_.Length -ge 1000}
  if (-not ($logfilematch)) {
    Write-Output "Log file $logfilematch does not exist or size is less than 1000KB. And Console has not been closed on server "
    Start-Sleep -Seconds 60
  } else {
    break
  }
}
Write-Output "Log file $logfilematch exists and size is greater than or equal to 1000KB - remember to delete Csv file or move to handled ."

#copy file and open log folder 
Add-Type -AssemblyName System.Speech
$synth = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
$logfilematch | Copy-Item -Force -Destination "C:\Users\$env:username\Documents\logs"  
write-host "Files has been copied"
write-host "Opening log folder"
$synth.Speak("Hey $env:USERNAME, File has been copied, Opening log folder")
Invoke-Item "C:\Users\$env:username\Documents\logs"

#find out why csv file is not moved to "done" folder on server after script.

