import fnmatch
import os
import numpy as np
import spc_io

def read_spc(path: str, pattern: str = "*.spc", export_to: str = "None"):
    '''
    Read multiple .spc files stored in path using spc-io package.
    Currently only supporting spc files with 1Y array.
    
    Parameters
    ----------
    path: str,
        path to directory where all the .spc files are stored.
    pattern: str, optional
        using fnmatch to filter for desired filenames.
        Default is "*.spc" thus reading all .spc files in path.
    export_to: str, optional
        file name if export to .csv is desired. 
        Default: "None"; export disabled.

    Returns
    -------
    ns: np.ndarray,
        np.array of all the read files. Rows: individual observations.
        Columns: wavelength.
    rs: np.ndarray,
        np.array of the actual wavelength.
    names: list,
        list of the filenames that were read in. 
    '''
    s = {}
    # Filter for desired filenames
    files = sorted([f.name for f in os.scandir(path)
                    if f.is_file if fnmatch.fnmatch(f.name, pattern)])
    
    # Open the files, store them as key,value pairs in a dict
    for i, file in enumerate(files):
        with open(path + file, "rb") as f:
            spc = spc_io.SPC.from_bytes_io(f) 
            s[file] = spc[0].yarray
    rs = np.array(spc[0].xarray)

    ns = np.array(list(s.values()))
    names = files # placeholder till cleaner is active. 
    
    if export_to != "None":
        # make top row wavelengths
        ns = np.insert(ns, 0, rs, axis=0)
        np.savetxt(export_to, ns, delimiter=",")

    # np.array for spectra, the wavelengths, cleaned filed names
    return ns, rs, names