const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
const log = require('loglevel');

const usbDetect = require('usb-detection');

const HelpersCtrl = require('../controllers/helpers');

const java = async () => {

    const helpersCtrl = new HelpersCtrl();

    if (process.env.CLIENT_SECURE_ACCESS_MODULE == 'true') {
        const peripherals = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'configs', 'peripherals.json')));

        if (peripherals.cardprinter && peripherals.cardprinter.using && peripherals.cardprinter.devicename == 'Zebra ZC350 USB Card Printer') {
            usbDetect.find((err, devices) => {
                const cardprinterReader = devices.find((f) => f.deviceName == 'Smartcard Device' && f.manufacturer == 'Elatec');
                if (cardprinterReader) {
                    log.info('Disabling card reader on Zebra ZC350 USB Card Printer');
                    const disableCardprinterReader = exec('%SYSTEMROOT%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -Command "Disable-PnpDevice -InstanceId \'USB\\VID_'+(cardprinterReader.vendorId).toString(16).padStart(4, '0')+'&PID_'+(cardprinterReader.productId).toString(16).padStart(4, '0')+'\\'+cardprinterReader.serialNumber+'\' -Confirm:$false"', (error, stdout, stderr) => { });
                }
            });
        }

        await helpersCtrl.samSmartCardLibStart();

        process.on('exit', () => {
            helpersCtrl.samSmartCardLibStop();
        });
    }

}

module.exports = java;
