use interim_pgtypes::pg_attribute::PgAttribute;
use serde::{Deserialize, Serialize};
use strum::{EnumIter, EnumString};

pub const RFC_3339_S: &str = "%Y-%m-%dT%H:%M:%S";

/// Struct defining how a field's is displayed and how it accepts input in UI.
#[derive(Clone, Debug, Deserialize, EnumIter, EnumString, PartialEq, Serialize, strum::Display)]
#[serde(tag = "t", content = "c")]
pub enum Presentation {
    Array { inner: Box<Presentation> },
    Dropdown { allow_custom: bool },
    Text { input_mode: TextInputMode },
    Timestamp { format: String },
    Uuid {},
}

impl Presentation {
    /// Returns a SQL fragment for the default data type for creating or
    /// altering a backing column, such as "integer", or "timestamptz".
    pub fn attr_data_type_fragment(&self) -> String {
        match self {
            Self::Array { inner } => format!("{0}[]", inner.attr_data_type_fragment()),
            Self::Dropdown { .. } | Self::Text { .. } => "text".to_owned(),
            Self::Timestamp { .. } => "timestamptz".to_owned(),
            Self::Uuid { .. } => "uuid".to_owned(),
        }
    }

    /// Generate the default presentation based on an existing column's type.
    /// Returns None if no default presentation exists.
    pub fn default_from_attr(attr: &PgAttribute) -> Option<Self> {
        match attr.regtype.to_lowercase().as_str() {
            "text" => Some(Self::Text {
                input_mode: TextInputMode::MultiLine {},
            }),
            "timestamp" => Some(Self::Timestamp {
                format: RFC_3339_S.to_owned(),
            }),
            "uuid" => Some(Self::Uuid {}),
            _ => None,
        }
    }

    /// Bet the web component tag name to use for rendering a UI cell.
    pub fn cell_webc_tag(&self) -> String {
        match self {
            Self::Array { .. } => todo!(),
            Self::Dropdown { .. } => "cell-dropdown".to_owned(),
            Self::Text { .. } => "cell-text".to_owned(),
            Self::Timestamp { .. } => "cell-timestamp".to_owned(),
            Self::Uuid {} => "cell-uuid".to_owned(),
        }
    }
}

impl Default for Presentation {
    /// Defaults to [`Self::Text`] as a reasonable fallback. The [`Default`]
    /// trait is implemented for convenience, but in the vast majority of cases
    /// the presentation value should be well defined and this should not be
    /// called directly.
    fn default() -> Self {
        Self::Text {
            input_mode: Default::default(),
        }
    }
}

#[derive(Clone, Debug, Deserialize, EnumString, EnumIter, PartialEq, Serialize, strum::Display)]
#[serde(tag = "t", content = "c")]
pub enum TextInputMode {
    SingleLine {},
    MultiLine {},
}

impl Default for TextInputMode {
    fn default() -> Self {
        Self::MultiLine {}
    }
}
