
import os, json
from .package import Package
from .errors import *

class PackageManager:
	def __init__(self, vfs):
		self.vfs = vfs
		self.package_map = {}
		self.package_list = []
		self.main_package = None

	def get_package_meta(self, filepath):
		if not os.path.exists(filepath):
			raise FilepathNotFound(filepath)
		gamepkg_path = os.path.join(filepath, 'gamepackage.json')
		if not os.path.exists(gamepkg_path):
			raise GamePackageMissing(gamepkg_path)
		meta = json.load(open(gamepkg_path))
		if 'name' not in meta or 'type' not in meta:
			raise GamePackageMalformed(gamepkg_path)
		return meta

	def set_main_package(self, filepath):
		meta = self.get_package_meta(filepath)
		if meta['type'] != 'main':
			raise InvalidPackageType(filepath, meta['type'])
		vfs_path = f'/main/'
		self.vfs.mount(filepath, vfs_path, 0)
		new_package = Package(type('', (object,), meta), vfs_path, self.vfs)
		self.main_package = new_package

	def include_package(self, filepath):
		meta = self.get_package_meta(filepath)
		if meta['name'] in self.package_map:
			raise PackageAlreadyLoaded(meta['name'])
		vfs_path = f'/include/{meta["name"]}'
		self.vfs.mount(filepath, vfs_path, 0) 
		new_package = Package(type('', (object,), meta), vfs_path, self.vfs)
		self.package_map[meta['name']] = new_package
		self.package_list.insert(0, new_package)