use std::path::PathBuf;

#[derive(Debug, Clone)]
pub enum LaunchKind {
    Edit,
    Cd,
    Open,
}

#[derive(Clone)]
pub struct LocItem {
    pub alias: String,
    pub path: PathBuf,
    pub lkind: LaunchKind,
    pub selected: bool,
    pub filter: bool,

    /// highest = last accessed
    pub access_scr: u32,
}

pub enum SortKind {
    LastAccessed,
    Alphabetic,
}

pub struct LocList {
    pub items: Vec<LocItem>,
    pub filtered_items: Vec<LocItem>,
    pub skind: SortKind,
}

impl LocList {
    pub fn new() -> Self {
        Self {
            items: Vec::new(),
            filtered_items: Vec::new(),
            skind: SortKind::LastAccessed,
        }
    }

    pub fn sort(&mut self) {
        match self.skind {
            SortKind::LastAccessed => {
                self.filtered_items
                    .sort_by(|a, b| a.access_scr.cmp(&b.access_scr));
                }
            SortKind::Alphabetic => {
                self.filtered_items.sort_by(|a, b| a.alias.cmp(&b.alias));
            }
        }
    }

    pub fn apply_filter(&mut self, entry_buff: &str) {
        self.filtered_items = self
            .items
            .iter()
            .filter(|item| item.alias.contains(entry_buff))
            .cloned()
            .collect();
        self.select_reset();
    }

    fn select_reset(&mut self) {
        if let Some(sel) = self.filtered_items.iter().position(|i| i.selected) {
            self.filtered_items[sel].selected = false;
            self.filtered_items[0].selected = true;
            return;
        }
    }

    pub fn select(&mut self, up: bool) {
        let len = self.filtered_items.len();
        if len == 0 {
            return;
        }

        if let Some(sel) = self.filtered_items.iter().position(|i| i.selected) {
            self.filtered_items[sel].selected = false;
            let next = if !up {
                (sel + 1) % len
            } else {
                (sel + len - 1) % len
            };
            self.filtered_items[next].selected = true;
            return;
        } else {
            self.filtered_items[0].selected = true;
            return;
        }
    }
}

