use crate::model::Texture;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::{self, *};
use std::path::Path;

#[derive(Default, Deserialize, Serialize)]
pub struct MetadataFile {
    pub textures: Vec<Texture>,
}

impl MetadataFile {
    pub fn load(path: &Path) -> io::Result<Self> {
        if !path.exists() {
            return Ok(Default::default());
        }

        let file = fs::File::open(path)?;
        let buf_reader = io::BufReader::new(file);

        let collection: Self = serde_json::from_reader(buf_reader)?;

        Ok(collection)
    }

    pub fn from_iterator<'a, I>(i: I) -> Self
    where
        I: Iterator<Item = &'a Texture>,
    {
        MetadataFile {
            textures: i.map(|tex| tex.clone()).collect(),
        }
    }

    pub fn store(self, path: &Path) -> io::Result<()> {
        let mut path_tmp = path.to_path_buf();
        assert!(path_tmp.set_extension("js.tmp"));

        let mut base = path.to_path_buf();
        base.pop();
        fs::create_dir_all(&base)?;

        let mut file = fs::File::create(&path_tmp)?;
        serde_json::to_writer(&mut file, &self)?;
        file.flush()?;
        drop(file);

        fs::rename(path_tmp, path)
    }
}
