use lib_provisioning *

# > TaskServs Delete
export def "main delete" [
    name?: string       # Server hostname in settings
    ...args                 # Args for create command 
    --infra (-i): string     # Infra directory 
    --keepstorage    # keep storage
    --settings (-s): string # Settings path 
    --yes (-y)      # confirm delete
    --outfile (-o): string  # Output file
    --serverpos (-p): int   # Server position in settings 
    --check (-c)     # Only check mode no servers will be created 
    --wait (-w)      # Wait servers to be created 
    --select: string # Select with task as option 
    --debug (-x)     # Use Debug mode
    --xm             # Debug with PROVISIONING_METADATA 
    --xc             # Debuc for task and services locally PROVISIONING_DEBUG_CHECK 
    --xr             # Debug for remote servers PROVISIONING_DEBUG_REMOTE 
    --xld            # Log level with DEBUG PROVISIONING_LOG_LEVEL=debug 
    --metadata       # Error with metadata (-xm)
    --notitles       # not tittles
    --helpinfo (-h)  # For more details use options "help" (no dashes)
    --out: string    #  Print Output format: json, yaml, text (default)
]: nothing -> nothing {
    if ($out | is-not-empty) {
        $env.PROVISIONING_OUT = $out 
        $env.PROVISIONING_NO_TERMINAL = true
    }
    provisioning_init $helpinfo "taskservs delete" $args
    #parse_help_command "server create" $name --ismod --end
    #print "on taskservs main delete"
    if $debug { $env.PROVISIONING_DEBUG = true } 
    if $metadata { $env.PROVISIONING_METADATA = true } 
    if $name != null and $name != "h" and $name != "help" {
        let curr_settings = (find_get_settings --infra $infra --settings $settings)
        if ($curr_settings.data.servers | find $name| length) == 0 {
           _print $"🛑 invalid name ($name)" 
           exit 1
        }
    }
    let task = if ($args | length) > 0 { 
        ($args| get 0) 
    } else { 
        let str_task = (($env.PROVISIONING_ARGS? | default "") | str replace "delete " " " ) 
        let str_task = if  $name != null { 
           ($str_task | str replace $name "") 
        } else {
            $str_task
        } 
        ($str_task | str trim | split row " " | get -o 0 | default "" |
            split row "-" | get -o 0 | default  "" | str trim )
    } 
    let other = if ($args | length) > 0 { ($args| skip 1) } else { "" } 
    let ops = $"($env.PROVISIONING_ARGS? | default "") " | str replace $"($task) " "" | str trim
    let run_delete = { 
        let curr_settings = (find_get_settings --infra $infra --settings $settings)
        $env.WK_CNPROV = $curr_settings.wk_path
        on_delete_taskservs $curr_settings $keepstorage $wait $name $serverpos 
    }
    match $task {
        "" if $name == "h" => { 
            ^$"($env.PROVISIONING_NAME)" -mod takserv delete --help --notitles
        },
        "" if $name == "help" => { 
            ^$"($env.PROVISIONING_NAME)" -mod takserv delete --help
            _print (provisioning_options "delete")
        },
        "" => { 
            if not $yes or not (($env.PROVISIONING_ARGS? | default "") | str contains "--yes")  {
                _print $"Run (_ansi red_bold)delete servers(_ansi reset) (_ansi green_bold)($name)(_ansi reset) type (_ansi green_bold)yes(_ansi reset) ? " 
                let user_input = (input --numchar 3)
                if $user_input != "yes" and $user_input != "YES"  {
                   exit 1
                }
            }
            let result = desktop_run_notify $"($env.PROVISIONING_NAME) servers delete" "-> " $run_delete --timeout 11sec
        },
        _ => { 
            if $task != "" { _print $"🛑 invalid_option ($task)" } 
            _print $"\nUse (_ansi blue_bold)($env.PROVISIONING_NAME) -h(_ansi reset) for help on commands and options"
        }
    } 
     if not $env.PROVISIONING_DEBUG { end_run "" } 
} 
export def on_delete_taskservs [
  settings: record   # Settings record 
  keep_storage: bool # keep storage
  wait: bool         # Wait for creation
  hostname?: string  # Server hostname in settings
  serverpos?: int    # Server position in settings 
]: nothing -> record {
    #use lib_provisioning * 
    #use utils.nu *
# TODO  review 
    return { status: true, error: "" }

    let match_hostname = if $hostname != null and $hostname != "" {  
        $hostname  
    } else if $serverpos != null  { 
        let total = $settings.data.servers | length
        let pos = if $serverpos == 0 { 
            _print $"Use number form 1 to ($total)"
            $serverpos
        } else if $serverpos <= $total { 
            $serverpos - 1
        } else { 
            (throw-error $"🛑 server pos" $"($serverpos) from ($total) servers" 
            "on_create" --span (metadata $serverpos).span)
            exit 1
        }
        ($settings.data.servers | get $pos).hostname
    }
   _print $"Delete (_ansi blue_bold)($settings.data.servers | length)(_ansi reset) server\(s\) in parallel (_ansi blue_bold)>>> 🌥  >>> (_ansi reset)\n"
    $settings.data.servers | enumerate | par-each { |it| 
        if $match_hostname == null or $match_hostname == "" or  $it.item.hostname == $match_hostname  { 
            if not (mw_delete_server $settings $it.item $keep_storage false) {
                return false
            }
           _print $"\n(_ansi blue_reverse)----🌥 ----🌥 ----🌥 ---- oOo ----🌥 ----🌥 ----🌥 ---- (_ansi reset)\n"
        } 
    }
    for server in $settings.data.servers {  
        let already_created = (mw_server_exists $server false)
        if ($already_created) {
           return { status: false, error: $"($server.hostname) created" }
        }
    }
    { status: true, error: "" }
} 
