import os

from cellmeta import CellMeta
from eisgenerator import EisSpectra
from parseerror import ParseError
from chargefile import ChargeFile


class SpectraFile:
	def __init__(self, filename: str, cellid: int, step: int, substep: int, charge_files: list[ChargeFile], total_cells: int):
		self.cellid = cellid
		self.step = step
		self.substep = substep
		self.filename = filename
		self.temperature = -1.0
		self.ocv = -1.0
		self.meta = CellMeta(cellid, step, substep, charge_files, total_cells)
		self.filename = os.path.split(filename)[1]

		self.spectra = EisSpectra.loadFromDisk(filename)
		header = self.spectra.header.split('"')[1].split(',')
		self.temperature = float(header[2])
		self.ocv = float(header[3])

		if int(header[0]) != step or int(header[1]) != cellid:
			raise ParseError(f"file name and file content of SpectraFile {filename} do not match")

	def write(self, directory: str):
		metaList = [float(self.step), float(self.substep), float(self.cellid), float(self.meta.cell_group), float(self.temperature), float(self.ocv),
			float(self.meta.charge_cycles), float(self.meta.thermal_cycles), float(self.meta.last_avg_cap), float(self.meta.last_avg_cap_step),
			float(self.meta.last_cap), float(self.meta.last_cap_step), float(self.meta.cap_esitmate), float(self.meta.soc), float(self.meta.soc_estimate)]
		self.spectra.setLabels(metaList)
		self.spectra.model = "Unkown"
		meta_dsc_strings = ["step", "substep", "cellid", "cell_group", "temparature", "ocv", "charge_cycles", "thermal_cycles",
			"last_avg_cap", "last_avg_step", "last_cap", "last_cap_step", "cap_estimate", "soc", "soc_estimate"]
		self.spectra.headerDescription = "File origin"
		self.spectra.header = "CoinCellHell mesurement file"
		self.spectra.labelNames = meta_dsc_strings
		self.spectra.saveToDisk(os.path.join(directory, self.filename))

