import {
  CliFlagInput,
  CliLeaf,
  CliStringInput,
  CliTerseError
} from '@alwaysai/alwayscli';
import { yesCliInput } from '../../cli-inputs';
import { checkUserIsLoggedInComponent } from '../../components/user';
import {
  deviceSelectComponent,
  getTargetHostnameComponent
} from '../../components/device';
import { REMOTE_AAI_CFG_DIR_LINUX } from '../../paths';
import { Spinner, SshSpawner } from '../../util';
import { posix } from 'path';

async function getCurrentDate() {
  const dateOb = new Date();
  const day = `0${dateOb.getDate()}`.slice(-2);
  const month = `0${dateOb.getMonth() + 1}`.slice(-2);
  const year = dateOb.getFullYear();
  const hour = `0${dateOb.getHours()}`.slice(-2);
  const minute = `0${dateOb.getMinutes()}`.slice(-2);
  const second = `0${dateOb.getSeconds()}`.slice(-2);

  return `${year}${month}${day}-${hour}${minute}${second}`;
}

export const deviceClean = CliLeaf({
  name: 'clean',
  description: 'Clean the alwaysAI configurations from a device',
  namedInputs: {
    yes: yesCliInput,
    device: CliStringInput({
      description: 'Device UUID'
    }),
    backup: CliFlagInput({
      description: 'Keep a copy of the device configuration as a backup'
    })
  },
  async action(_, { yes, device, backup }) {
    await checkUserIsLoggedInComponent({ yes });
    const deviceSelectOut = await deviceSelectComponent({
      yes,
      deviceId: device
    });

    const targetHostname = await getTargetHostnameComponent({
      yes,
      device: deviceSelectOut.device
    });
    if (targetHostname === undefined) {
      throw new CliTerseError(
        'Cannot access selected device! The device hostname is unknown.'
      );
    }

    const spawner = SshSpawner({
      targetHostname,
      targetPath: REMOTE_AAI_CFG_DIR_LINUX
    });
    if (backup === true) {
      const BACKUP_REMOTE_AAI_CFG_DIR_LINUX = posix.join(
        '~',
        '.config',
        `alwaysai.bak.${await getCurrentDate()}`
      );
      const spinner = Spinner(
        `Backing up device configuration to ${BACKUP_REMOTE_AAI_CFG_DIR_LINUX}`
      );
      try {
        await spawner.run({
          exe: 'cp',
          args: [
            '-r',
            REMOTE_AAI_CFG_DIR_LINUX,
            BACKUP_REMOTE_AAI_CFG_DIR_LINUX
          ]
        });
        spinner.succeed();
      } catch (exception) {
        spinner.fail();
        throw exception;
      }
    }
    const spinner = Spinner('Remove target device configuration');
    try {
      await spawner.sanatizedrimraf();
      spinner.succeed();
    } catch (exception) {
      spinner.fail();
      throw exception;
    }
  }
});
