use std::fmt::{self, Write};

// use libterm::TermKey;

use libterm::TermKey;

use super::map::Prefix;

#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct KeySeq(Vec<TermKey>);

impl KeySeq {
    pub fn one<I: Into<TermKey>>(k: I) -> Self {
        Self(vec![k.into()])
    }

    pub fn empty() -> Self {
        Self(vec![])
    }

    pub fn push<I: Into<TermKey>>(&mut self, k: I) {
        self.0.push(k.into());
    }

    pub fn clear(&mut self) {
        self.0.clear();
    }
}

impl Prefix for KeySeq {
    fn prefix(&self) -> Option<Self> {
        self.0.split_last().map(|(_, vs)| vs.to_vec()).map(Self)
    }
}

impl<K: Into<TermKey>, I: IntoIterator<Item = K>> From<I> for KeySeq {
    fn from(value: I) -> Self {
        Self(value.into_iter().map(Into::into).collect())
    }
}

impl fmt::Display for KeySeq {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, key) in self.0.iter().enumerate() {
            if i != 0 {
                f.write_char('+')?;
            }
            fmt::Debug::fmt(key, f)?;
        }
        Ok(())
    }
}
