/**
 * Add recipe override confirmation to keyboard window "Alphanumeric_Assistant_Module"
 */
class Alphanumeric_Assistant_Module {
    /**
     * @returns {Alphanumeric_Assistant_Module}
     */
    static create() {
        return new Alphanumeric_Assistant_Module();
    }

    constructor() {
		this.isFirstSubmit = true;
	}

    /**
     * @param {ViewModel} viewModel 
     */
    init(viewModel) {
		// Find keyboard HTML instance in keyboard window
		this.keyboard = viewModel?.getChildByName('Keyboard')?.getDomRef();
		if (this.keyboard) {
			// Store original _submit function before override
			this.keyboardSubmitOrig = this.keyboard._submit.bind(this.keyboard);
			if (this.keyboardSubmitOrig) {
				// Override _submit with custom implementation
				this.keyboard._submit = () => {
					this.keyboardSubmitOverride();
				};
			} else {
				sigApi.debug.error('cm_alphanumeric_assistant.js: Keyboard instance has no valid _submit function!');
			}
			// Store original _change function before override
			this.keyboardChangeOrig = this.keyboard._change.bind(this.keyboard);
			if (this.keyboardChangeOrig) {
				// Override _submit with custom implementation
				this.keyboard._change = (newval, oldval) => {
					this.keyboardChangeOverride(newval, oldval);
				};
			} else {
				sigApi.debug.error('cm_alphanumeric_assistant.js: Keyboard instance has no valid _check function!');
			}
		} else {
			sigApi.debug.error('cm_alphanumeric_assistant.js: Could not find keyboard instance in keyboard window!');
		}		
        this._initialized = true;
        this._active = false;
    }
	
	keyboardChangeOverride(newval, oldval) {
		// Call original change function this.keyboardChangeOrig(newval, oldval);
		this.keyboardChangeOrig(newval, oldval);
		// 
		if (this.keyboard.isactive) {
			// Reset first submit flag on input change
			this.isFirstSubmit = true;
			// Reset NamesCheckOk on input change
			sigApi.datapointManager.writeDataPoint('10:ToolsName1.NamesCheckOk', 0);
		}
	}
	
	keyboardSubmitOverride() {
		// Check if input is valid recipe file name
		if (this.keyboard.keyboardvalue.replace(/ /g, "") === "" || this.keyboard.keyboardvalue.includes("/") ||  this.keyboard.keyboardvalue.includes("\\")) {
			// Invalid input - open info window and wait for user to select new name
			sigApi.datapointManager.writeDataPoint('10:ToolsName1.NameEmpty', 1);
			sigApi.windowManager.openWindowByWindowIndex(44);
		} else {
			// Valid input - close info window and handle already existing file
			sigApi.datapointManager.writeDataPoint('10:ToolsName1.NameEmpty', 0);
			const wnd_ToolsNameIsEmpty = sigApi.windowManager.getWindowByWindowIndex(44);
			if (wnd_ToolsNameIsEmpty && wnd_ToolsNameIsEmpty.isOpen()){
				wnd_ToolsNameIsEmpty.close();
			}
			
			// First submit - check if the chosen name already exists
			if (this.isFirstSubmit) {
				this.isFirstSubmit = false;
				const newname = this.keyboard.keyboardvalue.toLowerCase();
				// Check if recipe file already exists
				sigApi.fileManager.info(`c:/userdata/recipe/${newname}`).then((res) => {
					// Recipe already exists - open info window and wait for user to select new name or confirm override
					sigApi.windowManager.openWindowByWindowIndex(38);
					sigApi.datapointManager.writeDataPoint('10:ToolsName1.NameAlreadyExists', 1);
				}).catch((err) => {
					// Recipe does not exist - name is valid
					sigApi.datapointManager.writeDataPoint('10:ToolsName1.NameAlreadyExists', 0);
					sigApi.datapointManager.writeDataPoint('10:ToolsName1.NamesCheckOk', 1);
					this.keyboardSubmitOrig();
				});
			// Second submit - the chosen name already exists and the user confirmed the override
			} else {
				const wnd_ToolsNameAlreadyExists = sigApi.windowManager.getWindowByWindowIndex(38);
				if (wnd_ToolsNameAlreadyExists && wnd_ToolsNameAlreadyExists.isOpen()){
					wnd_ToolsNameAlreadyExists.close();
				}								
				sigApi.datapointManager.writeDataPoint('10:ToolsName1.NameAlreadyExists', 0);
				sigApi.datapointManager.writeDataPoint('10:ToolsName1.NamesCheckOk', 1);
				this.keyboardSubmitOrig();
			}
		}
	}

    /**
     * @param {ViewModel} viewModel 
     */
    cleanUp(viewModel) {
        this.keyboard._submit = this.keyboardSubmitOrig;
		this.keyboardSubmitOrig = undefined;
		this.keyboard._change = this.keyboardChangeOrig;
		this.keyboardChangeOrig = undefined;
		this.keyboard = undefined;
        this._initialized = false;
    }

    /**
     * @param {boolean} active 
     */
    onActiveChanged(active) {
        this._active = active;
    }

}

// Register the Alphanumeric_Assistant_Module for the corresponding keyboard window
window.registerKeyboardModule('Alphanumeric_Assistant', Alphanumeric_Assistant_Module.create);
