"""
    This example script imports a set of spectral files from a folder and
    creates a workset from that dataset.
"""
import umetrics
import glob
import tempfile
from tkinter import messagebox, Tk
import xml.etree.ElementTree as ET

def show_message(message):
    # Show a tkinter messagebox with the message.
    tk_main=Tk()
    tk_main.withdraw()
    messagebox.showinfo(title='Create spectral project', message=message)
    tk_main.destroy()

def run():
    show_message('This script will import a number of NIR spectra, create a new project, SNV filter the data and fit a PCA model.')
    # Close the current open project
    project = umetrics.SimcaApp.get_active_project()
    if project.is_open:
        if not umetrics.simca.ProjectHandler.close_project(project, True):
            return
        
    # The paths for data files and where the project should be saved
    scriptpath = os.path.dirname(os.path.realpath(__file__))
    datapath = os.path.join(scriptpath, 'data/*.spc')
    projectpath=os.path.join(tempfile.gettempdir(), 'spectralproject.usp')
    if os.path.isfile(projectpath):
        os.remove(projectpath)

    # Read all spectral files (*.spc) from a directory
    files = glob.glob(datapath)

    # Create an XML tree with the spc open options.
    # If we don't supply these options, SIMCA will popup a dialog and ask for them.
    spcoptions=ET.Element('Settings')
    spcoptions.set('IncludeOrdinalValues', '1')
    spcoptions.set('IncludeAllValues', '1')
    spcoptions.set('IncludeXStartPt', '')
    spcoptions.set('IncludeXEndPt', '')
    spcoptions.set('NumberOfIncludedIntervals', '0')
    spcoptions.set('UseAverage', '0')

    data = umetrics.impdata.read_file(files, openoptions=ET.tostring(spcoptions))

    # Specify primary and secondary ID
    # Set first row to primary variable ID
    data.importspec.set_row_type(0, umetrics.impdata.ImportSpecification.rowtype.primaryvarid)
    # Set the wavenumbers in the second row to secondary variables IDs
    data.importspec.set_row_type(1, umetrics.impdata.ImportSpecification.rowtype.secondaryvarid)
    # Set the first column in the second row to 'Wave Number'. Then the secondary ID will get the correct name
    data.set(1,0, 'Wave Number')

    # Set first column to primary observation ID
    data.importspec.set_col_type(0, umetrics.impdata.ImportSpecification.columntype.primaryobsid)
    # Set second colum to secondary observation ID
    data.importspec.set_col_type(1, umetrics.impdata.ImportSpecification.columntype.secondaryobsid)
    # And the third
    data.importspec.set_col_type(2, umetrics.impdata.ImportSpecification.columntype.secondaryobsid)

    # Create a new project
    project = umetrics.simca.ProjectHandler.create_project(projectpath)

    # Create the dataset
    ds_num = project.create_dataset(data, "TheDataset")

    # Set the project as the active project in SIMCA to be able to show plots
    umetrics.SimcaApp.set_active_project(project)

    # Filter the dataset using SNV
    filter=project.create_filter(ds_num)
    filter.add_filter_type(umetrics.simca.filtertype.snv)
    filter.apply_filter('snv_filtered')
    ds_num = next(info.ID for info in project.get_dataset_infos() if info.name == 'snv_filtered')

    # Create a workset for the model
    workset = project.create_workset('snv_filtered')

    # Change scaling to center for all variables
    workset.set_variable_scale_type([], umetrics.simca.scaletype.ctr)

    # Exclude the first three variables
    workset.exclude_variables([0, 1, 2])

    # Create the model and autofit
    model = workset.create_model()
    project.fit_model(model[0])

    # Save it.
    project.save()

    # Create Summary of fit plot and score scatter plot
    builder = umetrics.SimcaApp.plot_list_builder()
    builder.score_scatter_plot()

if __name__ == "__main__":
    run()