use crate::err::SJFLError;
use crate::value::Value;
use crate::err::Span;
use super::{Parse, skip_whitespaces_and_comments, Session};

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct List {
    pub data: Vec<Box<Value>>
}

impl Parse for List {

    fn parse(s: &[u8], mut ind: usize, session: &mut Session) -> Result<(Self, usize), SJFLError> {
        let mut data = vec![];

        if s[ind] != b'[' {
            return Err(SJFLError::UnexpectedChar(s[ind], Span::from_index(ind)));
        }

        ind += 1;

        loop {
            ind = skip_whitespaces_and_comments(s, ind)?;

            if s[ind] == b']' {
                break;
            }

            let (v, new_ind) = Value::parse(s, ind, session)?;
            ind = new_ind;
            data.push(Box::new(v));

            ind = skip_whitespaces_and_comments(s, ind)?;

            if s[ind] == b',' {
                ind += 1;
            }

            else if s[ind] == b']' {
                break;
            }

            else {
                return Err(SJFLError::UnexpectedChar(s[ind], Span::from_index(ind)));
            }

        }

        Ok((List { data }, ind + 1))
    }

}