"""
The module 'read_write_spectra' provides functionality for reading and storing (infrared) spectra in different
formats. The focus lies on spectra that can be imported exported by the Calcmet software of Gasmet Technologies Oy.
"""

import os
import pandas as pd

from pathlib import Path
from typing import Literal, Union


def read_spectrum(file_path:  str | os.PathLike[str],
                  file_extension: Literal['dx', 'txt']='dx') -> pd.DataFrame | None:

    file_extension = os.path.splitext(os.path.basename(file_path))[1].lower()
    # use lowercase to allow for unique check of file extension

    if file_extension == '.dx':

        print(f'\nReading spectra in DX-format is not yet implemented in tailpype !')

        return pd.DataFrame()

    elif file_extension == '.txt':

        df_spectrum = pd.read_csv(filepath_or_buffer=file_path, sep=' ', header=None, encoding='ascii').\
            rename(columns={0: 'Wave number [cm-1]', 1: os.path.splitext(os.path.basename(file_path))[0]})

    else:
        raise 'File type of spectrum file could not be determined'

    return df_spectrum


def save_spectrum_as(df: pd.DataFrame, file_path: str | Path) -> None:
    # https: // old.iupac.org / jcamp / protocols / dxir01.pdf

    file_extension = os.path.splitext(os.path.basename(file_path))[1].lower()
    # use lowercase to allow for unique check of file extension

    if file_extension == '.dx':

        # open templates of DX-file to be filled with data
        with open(Path(os.path.join(Path(__file__).resolve().parent, 'templates', 'JCAMP‑DX template.dx'))) as fobj:
            jcamp_dx_file = fobj.read()

        df.iloc[:, 1] = df.iloc[:, 1] * 1e6
        df.iloc[:, 1] = df.iloc[:, 1].round(0).astype(int)
        # needed to match the number format

        jcamp_dx_file = jcamp_dx_file.replace(r'REPLACE WITH DATA !', df.to_string(index=False, header=False))

        with open(file_path, 'w') as fobj:
            fobj.write(jcamp_dx_file)

        return None

    elif file_extension == '.txt':

        print(f'\nStoring spectra in TXT-format is not yet implemented in tailpype !')

        return None
