// SPDX-License-Identifier: LGPL-2.1-or-later OR GPL-2.0-or-later OR MPL-2.0
// SPDX-FileCopyrightText: 2026 Gabriel Marcano <gabemarcano@yahoo.com>

use crate::error::Error;
use crate::metadata::Metadata;
use crate::metadata::MetadataRead;

use std::io;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;

/// Represents a Cart object that can be read from.
pub struct Cart<T: Read + Seek> {
    pub metadata: Metadata,
    io: T,
}

impl<T: Read + Seek> Cart<T> {
    /// Creates a [`Cart`] from the given IO object.
    ///
    /// # Errors
    ///
    /// See [`MetadataRead::read_sfc_metadata`] for details.
    pub fn try_from(io: T) -> Result<Self, Error> {
        let mut io = io;
        Ok(Self {
            metadata: io.read_sfc_metadata()?,
            io,
        })
    }

    /// Consumes the [`Cart`] and returns its internal data.
    pub fn release(self) -> (Metadata, T) {
        (self.metadata, self.io)
    }

    /// Computes the checksum of the [`Cart`].
    ///
    /// # Errors
    ///
    /// See [`Metadata::compute_checksum`] for details.
    pub fn checksum(&mut self) -> Result<u16, Error> {
        let mut io = &mut self.io;
        self.metadata.compute_checksum(&mut io)
    }
}

impl<T: Read + Seek> Read for Cart<T> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.io.read(buf)
    }
}

impl<T: Read + Seek> Seek for Cart<T> {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        self.io.seek(pos)
    }
}
