use std::path::{PathBuf,Path};
use std::collections::HashMap;
use core::error::Error;
use std::time::SystemTime;

mod lexer;

pub struct Tx {
    fragments: HashMap<String, Fragment>,
    sources: Vec<FragmentSource>,
}

#[derive(PartialEq,Eq,Debug,Clone)]
enum FragmentSource {
    File {
        path: PathBuf,
        loaded: SystemTime,
    },
    Static,
    External {
        key: String,
    },
}

struct Fragment {
    name: String,
    source: usize,
    sections: HashMap<String, Section>,
}

struct Section {
    name: String,
    ast_root: Token,
}

type Properties = HashMap<String, String>;

enum Token {
    Root(Vec<Token>),
    Fragment(String,Properties,Vec<Token>),
    Section(String,Properties,Vec<Token>),
    Text(String),

}

struct State {
}

impl Tx {
    pub fn new() -> Self {
        Self {
            fragments: HashMap::new(),
            sources: vec![Frament::Static],
        }
    }

    fn id_source(&mut self, src: &FragmentSource ) -> usize {
        for idx in 0..self.sources.len() {
            if self.sources[idx] == src {
                return idx;
            }
        }

        // Nothing found, add a new one
        let idx = self.sources.len();
        self.sources.push( src.clone() );
        idx
    }

    pub fn load_file(&mut self, path: &Path) -> Result<(),Box::<dyn Error>> {
        let time = if let Ok(meta) = path.metadata() {
            if let Ok(t) = meta.modified() {
                t
            } else if let Ok(t) = meta.created() {
                t
            } else {
                SystemTime::now()
            }
        } else {
            SystemTime.now()
        };

        let mut file = File::open( path )?;

        let mut ll = lexer::Lexer( &String::from_utf8( file.read()? )? );
        Ok(())
    }

    pub fn load_static(&mut self, data: &str) -> Result<(),Box::<dyn Error>> {

        Ok(())
    }

    pub fn load_external(&mut self, key: &str, data: &str) -> Result<(),Box::<dyn Error>> {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn lexing() {
        let data = r#"Leading comment: [|fragment "basic"|>Hello there <|fragment|] Trailing text"#;
        let ll = lexer::Lexer::new( &data );
        for sym in ll {
            if let lexer::Symbol::Error{line,row,what} = sym {
                println!("Error {}:{}: {}", line, row, what );
                break;
            } else {
                println!("Symbol: {:?}", sym );
            }
        }
    }
}
