/**
 * Demo how to use sigApi.recipeManager
 * 
 * demo setup:
 *   required user defined internal events
 *     * 'evtRecipeSave'
 *     * 'evtRecipeLoad'
 *   required directories and files
 *     * 'c:\temp\recipe.txt' expected to exist
 * 
 * copyright by Sigmatek GmbH & CoKG
 */

const TEST_DIR = 'c:/userdata/recipe';
const NAME_FILTER = '*.txt';

class SaveLoadTool {
    static init() {
        window.sigApiReadyPromise.then(() => {
            const codemodule = new SaveLoadTool();
        });
    }

    constructor() {
        this._registerEvents();
    }

    /**
     * @private
     * register to user defined events
     */
    _registerEvents() {

    /*    sigApi.eventMediator.subscribe(
            sigApi.events.getUserDefinedInternalEvent('CreateServiceFile'),
            () => {
                sigApi.datapointManager.readDataPoint('10:ToolsName1.FileName', 0)
                    .then((resolve) => {
                        this._onRecipeSave_Service(resolve.value);
                    });
            }
        );*/

        sigApi.eventMediator.subscribe(
            sigApi.events.getUserDefinedInternalEvent('CloseWindow64'),
            () => {
                window.window.sigApi.windowManager.closeWindowByWindowIndex(64);
            }
        );

         sigApi.eventMediator.subscribe(
            sigApi.events.getUserDefinedInternalEvent('SaveNewTool'),
            () => {sigApi.datapointManager.readDataPoint('10:Global_Set1.GlobalOn', 0)
                .then((resolve) => {
                    const GlobalOn = resolve.value;
                    if (GlobalOn === 1){
                        sigApi.datapointManager.writeDataPoint('10:ThermoSensorType1.FirstToolStart', 1);
                    }
                    else{
                        sigApi.datapointManager.writeDataPoint('10:ThermoSensorType1.FirstToolStart', 0);
                    }
                    sigApi.datapointManager.readDataPoint('10:ToolsName1.Tools_Name_Unsaved', 0)
                        .then((resolve) => {
                            sigApi.datapointManager.writeDataPoint('10:ToolsName1.Tools_Name', resolve.value);
                            const newname = resolve.value.toLowerCase();
                            this._onRecipeSave(newname);
                        });
                });
}
        );
        sigApi.eventMediator.subscribe(
            sigApi.events.getUserDefinedInternalEvent('LoadLastTool'),
            () => {
                sigApi.datapointManager.readDataPoint('10:ToolsName1.Tools_Name', 0)
                        .then((resolve) => {
                        const newname = resolve.value.toLowerCase();
                        this._onRecipeLoad(newname);
                    });
            }
        );

        sigApi.eventMediator.subscribe(
            sigApi.events.getUserDefinedInternalEvent('LoadNewTool'),
            () => {
                sigApi.datapointManager.readDataPoint('10:ToolsName1.Tools_Name_Unsaved', 0)
                    .then((resolve) => {

                        if (resolve.value !== "..") {
                            sigApi.datapointManager.writeDataPoint('10:ToolsName1.Alarm', 0);
                            sigApi.datapointManager.writeDataPoint('10:ToolsName1.Tools_Name', resolve.value);
                            this._onRecipeLoad(resolve.value);
                        }
                        else {
                            sigApi.datapointManager.writeDataPoint('10:ToolsName1.Alarm', 1);
                            sigApi.datapointManager.writeDataPoint('10:ToolsName1.Tools_Name', "ERROR");
                        }
                    });
            }
        );

    }

    /**
     * @private
     * log the result of sigApi.recipeManager.load
     */
    _onRecipeLoad(newname) {
        console.log('[SaveLoadTool] _onRecipeLoad()');
       // const dpne = 'c:/userdata/recipe//' + newname; //'c:\\temp\\recipe.txt';
        const dpne = 'c:/userdata/recipe/' + newname; //'c:\\temp\\recipe.txt';
        const filter1 = 0;
        const filter2 = 0;
        sigApi.recipeManager.load(dpne, filter1, filter2).then((res) => {
            sigApi.datapointManager.writeDataPoint('10:ToolsName1.Alarm', 0);
            sigApi.datapointManager.writeDataPoint('10:ToolsName1.Loaded', 1);
            sigApi.datapointManager.writeDataPoint('10:ThermoSensorType1.FirstToolStart', 0);
            console.log(`[SaveLoadTool] sigApi.recipeManager.load('${dpne}', ${filter1}, ${filter2}) uid: ${res.uid} dpne: ${res.dpne}`);
        }).catch((error) => {
            sigApi.datapointManager.writeDataPoint('10:ToolsName1.Alarm', 1);
            sigApi.datapointManager.writeDataPoint('10:ToolsName1.Loaded', 0);
            sigApi.datapointManager.writeDataPoint('10:ToolsName1.Tools_Name', "ERROR");
            console.log(`[SaveLoadTool] error in sigApi.recipeManager.load('${dpne}', ${filter1}, ${filter2}) uid: ${error.uid} status: ${error.status} errortxt: ${error.errortxt}`);
        });
    }

    /**
     * @private
     * log the result of sigApi.recipeManager.save
     */
    _onRecipeSave(newname) {
        console.log('[SaveLoadTool] _ onRecipeSave()');
       // const dpne = 'c:/userdata/recipe//' + newname; //'c:\\temp\\recipe.txt';
        const dpne = 'c:/userdata/recipe/' + newname; //'c:\\temp\\recipe.txt';
        const headertext = 'header row1\nrow2\nrow3\n\n';
        const filter1 = 0;
        const filter2 = 0;
        sigApi.recipeManager.save(dpne, headertext, filter1, filter2).then((res) => {
            sigApi.datapointManager.writeDataPoint('10:ToolsName1.Alarm', 0);
            sigApi.datapointManager.writeDataPoint('10:ToolsName1.Saved', 1);
            console.log(`[SaveLoadTool] sigApi.recipeManager.save('${dpne}', '${headertext}', ${filter1}, ${filter2}) uid: ${res.uid} dpne: ${res.dpne}`);
            sigApi.datapointManager.readDataPoint('10:ExistStandAlone1.s_Spritzbereit', 0)
                .then((resolve) => {if (resolve.value === 1) {sigApi.datapointManager.writeDataPoint('10:ToolsName1.SaveTool', 1);}
                });

     /*   sigApi.fileManager.readDir(TEST_DIR, NAME_FILTER, attributeIncludeFilter, attributeExcludeFilter).then((res) => {
            console.log(`[DemoApiFileManager] sigApi.fileManager.readDir('${TEST_DIR}', '${NAME_FILTER}', ${attributeIncludeFilter}, ${attributeExcludeFilter}) uid: ${res.uid}`);
            console.log(`[DemoApiFileManager]     parent: ${res.parent.dpne}`);
            for (let ii = 0, len = res.parent.nodes.length; ii < len; ii += 1) {
                const node = res.parent.nodes[ii];
                console.log(`[DemoApiFileManager]         nodes[${ii}]:`);
                console.log(`[DemoApiFileManager]             dpne: ${node.dpne}`);
                console.log(`[DemoApiFileManager]             size: ${node.size}`);
                console.log(`[DemoApiFileManager]             attribute: ${node.attribute}`);
            }
        }).catch((error) => {
            console.log(`[DemoApiFileManager] error in sigApi.fileManager.readDir('${TEST_DIR}', '${NAME_FILTER}', ${attributeIncludeFilter}, ${attributeExcludeFilter}) uid: ${error.uid} status: ${error.status} errortxt: ${error.errortxt}`);
        });*/

        }).catch((error) => {
            sigApi.datapointManager.writeDataPoint('10:ToolsName1.Alarm', 1);
            sigApi.datapointManager.writeDataPoint('10:ToolsName1.Saved', 0);
            //sigApi.datapointManager.writeDataPoint('10:ToolsName1.SaveOptimalTool', 0);
            console.log(`[SaveLoadTool] error in sigApi.recipeManager.save('${dpne}', '${headertext}', ${filter1}, ${filter2}) uid: ${error.uid} status: ${error.status} errortxt: ${error.errortxt}`);
        });
    }

    _onRecipeSave_Service(newname) {
        console.log('[SaveLoadTool] _ onRecipeSave()');
        const dpne = 'e://' + newname; //'c:\\temp\\recipe.txt';
        const headertext = 'header row1\nrow2\nrow3\n\n';
        const filter1 = 0;
        const filter2 = 0;
        sigApi.recipeManager.save(dpne, headertext, filter1, filter2).then((res) => {

            console.log(`[SaveLoadTool] sigApi.recipeManager.save('${dpne}', '${headertext}', ${filter1}, ${filter2}) uid: ${res.uid} dpne: ${res.dpne}`);

        }).catch((error) => {

            console.log(`[SaveLoadTool] error in sigApi.recipeManager.save('${dpne}', '${headertext}', ${filter1}, ${filter2}) uid: ${error.uid} status: ${error.status} errortxt: ${error.errortxt}`);
        });
    }

}

/**
 * Create the codemodule instance
 */
SaveLoadTool.init();
