/**
 * ./src/krill/prepare.d/welcome.tsx
 * penguins-eggs v.25.7.x / ecmascript 2020
 * author: Piero Proietti
 * email: piero.proietti@gmail.com
 * license: MIT
 * https://stackoverflow.com/questions/23876782/how-do-i-split-a-typescript-class-into-multiple-files
 */
import fs from 'fs';
import React from 'react';
import Utils from '../../../classes/utils.js';
import Network from '../../components/network.js';
import getAddress from '../../lib/get_address.js';
import getDns from '../../lib/get_dns.js';
import getDomain from '../../lib/get_domain.js';
import getGateway from '../../lib/get_gateway.js';
import getNetmask from '../../lib/get_netmask.js';
import selectAddressType from '../../lib/select_address_type.js';
import selectInterface from '../../lib/select_interface.js';
import { confirm } from './confirm.js';
/**
 * Network
 */
export async function network() {
    const i = {};
    const ifaces = fs.readdirSync('/sys/class/net/');
    i.iface = await Utils.iface();
    i.addressType = 'dhcp';
    i.address = Utils.address();
    i.netmask = Utils.netmask();
    i.gateway = Utils.gateway();
    i.dns = Utils.getDns();
    i.domain = Utils.getDomain();
    let dnsString = '';
    for (let c = 0; c < i.dns.length; c++) {
        dnsString += i.dns[c].trim();
        if (c < i.dns.length - 1) {
            dnsString += '; ';
        }
    }
    let networkElem;
    while (true) {
        networkElem = React.createElement(Network, { address: i.address, addressType: i.addressType, dns: dnsString, domain: i.domain, gateway: i.gateway, iface: i.iface, netmask: i.netmask });
        if (await confirm(networkElem, "Confirm Network datas?")) {
            break;
        }
        i.iface = await selectInterface(i.iface, ifaces);
        i.addressType = await selectAddressType();
        if (i.addressType === 'static') {
            i.address = await getAddress(i.address);
            i.netmask = await getNetmask(i.netmask);
            i.gateway = await getGateway(i.gateway);
            i.domain = await getDomain(i.domain);
            if (i.domain.at(0) !== '.') {
                i.domain = '.' + i.domain;
            }
            i.dns = (await getDns(dnsString)).split(';');
            dnsString = '';
            for (let c = 0; c < i.dns.length; c++) {
                dnsString += i.dns[c].trim();
                if (c < i.dns.length - 1) {
                    dnsString += '; ';
                }
            }
        }
    }
    return i;
}
