# Copyright (C) 2024 Michael Becker  <alcexhim@gmail.com>
# 
# This file is part of yaml2mcl.
# 
# yaml2mcl is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# yaml2mcl is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with yaml2mcl.  If not, see <https://www.gnu.org/licenses/>.

from framework import Guid
from .Section import Section

class SectionFile:

	def __init__(self, signature : str = None, version : float = 1.0, flags : int = 0):
		self.signature = signature
		self.sections = [ ]
		self.version = version
		self.flags = flags

	def add_section(self, section : Section):
		self.sections.append(section)

	def open(self, filename : str):

		self.filename = filename

	def save(self):

		f = open(self.filename, 'wb')
		
		if self.signature is not None:
			f.write(self.signature.encode('utf-8'))

		import struct
		ba = bytearray(struct.pack("f", self.version))
		f.write(ba)
		f.write(int.to_bytes(self.flags, 4, 'little'))

		section_count = len(self.sections)
		f.write(int.to_bytes(section_count, 4, 'little'))

		f.write(Guid.create().to_bytes())

		offset = 32 + (section_count * 32)
		lastLength = 0
		for sect in self.sections:
			offset += lastLength
			length = sect.get_length()
			
			f.write(str(sect.name).ljust(16, '\0').encode("utf-8"))
			f.write(int.to_bytes(offset, 4, 'little'))
			f.write(int.to_bytes(length, 4, 'little')) # compressed length for compressed sections
			f.write(int.to_bytes(length, 4, 'little')) # decompressed length for compressed sections
			f.write(int.to_bytes(len(sect.data), 4, 'little'))

			lastLength = length

		for sect in self.sections:
			sect.write_data(f)
		
		f.close()

