use std::ffi::OsString;

use clap::{Parser, ValueEnum};
use wayland_protocols_wlr::layer_shell::v1::client::zwlr_layer_surface_v1;

/// The target requested by the user.
#[derive(Clone, ValueEnum, PartialEq, Eq)]
pub(crate) enum RequestedTarget {
    /// The currently active window.
    Window,
    /// The entirety of the currently active output.
    Output,
    /// A custom region (chosen interactively).
    Region,
}

fn parse_anchor(s: &str) -> Result<zwlr_layer_surface_v1::Anchor, String> {
    let anchor = match s {
        "top-left" => zwlr_layer_surface_v1::Anchor::Top | zwlr_layer_surface_v1::Anchor::Left,
        "bottom-left" => {
            zwlr_layer_surface_v1::Anchor::Bottom | zwlr_layer_surface_v1::Anchor::Left
        }
        "top-right" => zwlr_layer_surface_v1::Anchor::Top | zwlr_layer_surface_v1::Anchor::Right,
        "bottom-right" => {
            zwlr_layer_surface_v1::Anchor::Bottom | zwlr_layer_surface_v1::Anchor::Right
        }
        _ => return Err(format!("{s} is not a valid anchor")),
    };
    Ok(anchor)
}

#[derive(Parser)]
#[clap(author, version = env!("SHOTMAN_VERSION"), about, long_about = None)]
pub struct Cli {
    /// Capture the given target into a screenshot.
    #[arg(
        short,
        long,
        value_name = "TARGET",
        required_unless_present = "print_dir"
    )]
    pub(crate) capture: Option<RequestedTarget>,

    /// Automatically copy to clipboard.
    #[arg(short = 'C', long)]
    pub(crate) copy: bool,

    /// Use `PROG` as an image editor.
    ///
    /// `PROG` must be a program in the current `$PATH` or an absolute path.
    #[arg(short, long, value_name = "PROG", env, default_value = "gimp")]
    pub(crate) image_editor: OsString,

    /// When copying to clipboard, also offer mime type `text/uri-list`.
    ///
    /// This features is experimental. Many sandboxed applications have issues
    /// due to prioritizing this over `image/png`.
    #[arg(long)]
    pub unstable_copy_as_uri: bool,

    #[clap(short, long)]
    /// Log using specified verbosity.
    pub(crate) verbose: Option<log::Level>,

    /// Anchor thumbnail to this edge of the screen.
    #[clap(short, long, value_parser=parse_anchor, default_value="top-left")]
    pub(crate) anchor: zwlr_layer_surface_v1::Anchor,

    /// Print path to screenshots directory and exit.
    #[arg(short, long)]
    pub(crate) print_dir: bool,
}
