"""
    This example script adds new batches to an existing batch project
"""
import umetrics
import os
from tkinter import messagebox, Tk

def show_message(message):
    # Show a tkinter messagebox with the message.
    tk_main=Tk()
    tk_main.withdraw()
    messagebox.showinfo(title='Complement Batch Project', message=message)
    tk_main.destroy()

def run():
    show_message('This script will add new batches to an existing project and\n'+
                 'create a new batch evolution model group with the added batches.')
    # 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 path for the data file and where the project is located
    scriptpath = os.path.dirname(os.path.realpath(__file__))
    datapath = scriptpath + r'\Data\NewBatches.dif'
    projectpath = scriptpath + r'\Data\BatchProject.usp'
    importOptions = ''

    # Open the project
    project = umetrics.simca.ProjectHandler.open_project(projectpath)
    datafile = umetrics.impdata.read_file(datapath, openoptions = importOptions)

    # Set the project as the active project in SIMCA
    umetrics.SimcaApp.set_active_project(project)

    # Test that it is a batch project
    if not (project.is_batch_project) :
        raise Exception("The project must be a batch project!")

    # Specify primary and secondary ID and batch and phase ID
    # Set first row to primary variable ID
    datafile.importspec.set_row_type(0, umetrics.impdata.ImportSpecification.rowtype.primaryvarid)
    # Set first colum to primary observation ID
    datafile.importspec.set_col_type(0, umetrics.impdata.ImportSpecification.columntype.primaryobsid)
    # Exclude non used column
    datafile.importspec.set_col_type(1, umetrics.impdata.ImportSpecification.columntype.excluded)
    # Set batch ID
    datafile.importspec.set_col_type(2, umetrics.impdata.ImportSpecification.columntype.batchid)
    # Set phase ID
    datafile.importspec.set_col_type(3, umetrics.impdata.ImportSpecification.columntype.phaseid)

    # Create the dataset
    ds_num = project.create_dataset(datafile, "NewBatches")

    # Create a new workset from the first model group that we want to complement with new batches
    workset = project.new_as_workset(-1)

    # Add the new dataset with the new batches
    workset.add_dataset(ds_num)

    # Create and fit the models
    models = workset.create_model()
    for modelNumber in models :
        project.fit_model(modelNumber)
    
if __name__ == "__main__":
    run()