#!/usr/bin/env node

import { Hyprland } from '../../services/hyprland';
import child_process = require('child_process');
import * as lodash from 'lodash';
import * as shelljs from 'shelljs';
import { createLogger } from '../../logger';

const logger = createLogger('move-ws-to-output');

async function showMenu(menu: string, prompt: string) {
  const rofi = child_process.exec(
    `rofi -dmenu -i -p "${prompt}" -format`,
  );

  rofi.stdin.write(menu);
  rofi.stdin.end();

  let output = '';

  for await (const chunk of rofi.stdout) {
    output += chunk;
  }

  return output.trimEnd();
}

async function main() {
  logger.debug({ file: __filename }, 'Welcome to the move ws to output tool');
  const hyprland = new Hyprland();

  const workspaces = hyprland.getWorkspaces().map((workspace) => workspace.name);

  const dmenu = lodash.sortBy(workspaces).join('\n');

  const selectedWorkspace = await showMenu(dmenu, 'Select a Workspace');

  if (selectedWorkspace.length === 0) {
    return;
  }

  logger.debug({ selectedWorkspace }, 'Selected workspace');

  const outputs = hyprland.getOutputs();

  const outputMenu = lodash
    .sortBy(outputs, ['id', 'make', 'model', 'serial'])
    .map(
      (output) =>
        `${output.make} ${output.model} ${output.serial} (${output.name})`,
    )
    .join('\n');

  logger.debug({ outputMenu }, 'Spawning the menu');

  const selectedOutput = await showMenu(outputMenu, 'Select a Monitor');

  if (selectedOutput.length === 0) {
    return;
  }

  const selectedOutputMatch = selectedOutput.trim().match(/\([^)]+\)$/);
  let outputName: string | null = null;

  if (selectedOutputMatch !== null) {
    outputName = selectedOutputMatch[0].slice(1, -1);
  }

  if (typeof outputName === 'string') {
    const activeWorkspace = hyprland.getActiveWorkspace();
    logger.debug({ activeWorkspace: activeWorkspace.name }, 'Saving active workspace');

    const command = `hyprctl --batch "dispatch workspace name:${selectedWorkspace} ; dispatch movecurrentworkspacetomonitor ${outputName} ; dispatch workspace name:${activeWorkspace.name}"`;
    logger.debug(
      { selectedWorkspace, outputName, command },
      'Moving workspace to monitor',
    );
    const output = shelljs.exec(command);

    logger.debug(
      {
        output,
      },
      'Result of dispatch',
    );
  }
}

void main();
