//#region imports
import { CoreModels__NS__localhostIp127, Helpers__NS__info, Helpers__NS__taskStarted, UtilsNetwork__NS__isValidIp, UtilsTerminal__NS__confirm, UtilsTerminal__NS__input, UtilsTerminal__NS__pressAnyKeyToContinueAsync, UtilsTerminal__NS__select } from 'tnp-core/lib-prod';
import { BaseCliWorkerTerminalUI, } from 'tnp-helpers/lib-prod';
import { Instances } from './instances';
//#endregion
export class InstancesTerminalUI extends BaseCliWorkerTerminalUI {
    async headerText() {
        return null;
    }
    textHeaderStyle() {
        return 'slick';
    }
    getWorkerTerminalActions(options) {
        //#region @backendFunc
        const myActions = {
            getStuffFromBackend: {
                name: 'Get instances list',
                action: async () => {
                    Helpers__NS__info(`Fetching list...`);
                    const ctrl = await this.worker.getRemoteControllerFor({
                        methodOptions: {
                            calledFrom: 'Get instances backend terminal action',
                        },
                    });
                    const list = (await ctrl.getEntities().request())?.body.json || [];
                    console.log(list.map(c => `- ${c.id} ${c.name} ${c.ipAddress}`).join('\n'));
                    Helpers__NS__info(`Fetched ${list.length} entities`);
                    await UtilsTerminal__NS__pressAnyKeyToContinueAsync({
                        message: 'Press any key to go back to main menu',
                    });
                },
            },
            deleteInstance: {
                name: 'Delete instance',
                action: async () => {
                    Helpers__NS__info(`Fetching list...`);
                    const ctrl = await this.worker.getRemoteControllerFor({
                        methodOptions: {
                            calledFrom: 'Get stuff from backend action',
                        },
                    });
                    const list = (await ctrl.getEntities().request())?.body.json || [];
                    const choices = list.map(c => ({
                        name: `${c.id} ${c.name} ${c.ipAddress}`,
                        value: c.id,
                    }));
                    const id = await UtilsTerminal__NS__select({
                        question: 'Select instance to delete',
                        autocomplete: true,
                        choices: [{ name: '- back -', value: '' }, ...choices],
                    });
                    const instance = id && list.find(l => l.id === id);
                    if (instance) {
                        Helpers__NS__info(`Deleting instance with

              ip:${instance.ipAddress}
              name:${instance.name}

              `);
                        if (await UtilsTerminal__NS__confirm({
                            message: 'Are you sure you want this instance ?',
                        })) {
                            try {
                                Helpers__NS__taskStarted('Deleting instance');
                                await ctrl.delete(instance.id).request();
                                await UtilsTerminal__NS__pressAnyKeyToContinueAsync({
                                    message: 'Instance deleted. Press any key to go back to main menu',
                                });
                            }
                            catch (error) {
                                await UtilsTerminal__NS__pressAnyKeyToContinueAsync({
                                    message: 'Error deleting instance. Press any key to go back to main menu',
                                });
                            }
                        }
                    }
                },
            },
            insertDeployment: {
                name: 'Create new instance',
                action: async () => {
                    Helpers__NS__info(`Inserting new deployment`);
                    const ctrl = await this.worker.getRemoteControllerFor({
                        methodOptions: {
                            calledFrom: 'Insert new deployment action',
                        },
                    });
                    while (true) {
                        try {
                            //#region terminal form
                            const ipAddress = await UtilsTerminal__NS__input({
                                required: true,
                                question: 'Enter IP address of the instance',
                                validate: val => {
                                    if (val?.trim() === CoreModels__NS__localhostIp127) {
                                        return false;
                                    }
                                    if (val?.trim() === 'localhost') {
                                        return false;
                                    }
                                    return UtilsNetwork__NS__isValidIp(val);
                                },
                            });
                            const nameOfInstance = await UtilsTerminal__NS__input({
                                required: true,
                                question: 'Enter name of instance',
                                validate: val => {
                                    if (!val || val.trim() === '') {
                                        return false;
                                    }
                                    return val.trim().length > 3;
                                },
                            });
                            //#endregion
                            const instance = await ctrl
                                .insertEntity(new Instances().clone({
                                ipAddress,
                                name: nameOfInstance,
                            }))
                                .request()
                                .then(r => r.body.json);
                            await UtilsTerminal__NS__pressAnyKeyToContinueAsync({
                                message: `Instance (id=${instance.id}) created. Press any key to go back to main menu`,
                            });
                            break;
                        }
                        catch (error) {
                            //#region error handling
                            if (await UtilsTerminal__NS__confirm({
                                message: 'Error creating instance. Try again ?',
                            })) {
                                continue;
                            }
                            else {
                                break;
                            }
                            //#endregion
                        }
                    }
                },
            },
        };
        return {
            ...this.chooseAction,
            ...myActions,
            ...super.getWorkerTerminalActions({
                ...options,
                chooseAction: false,
            }),
        };
        //#endregion
    }
}
//# sourceMappingURL=instances.terminal-ui.js.map