import { app } from 'electron';
import AutoLaunch from 'auto-launch';
import * as fsp from 'fs/promises';
import * as path from 'path';

import {
  DESKTOP_APP_DISPLAY_NAME,
  isLegacyLinuxAutostartEntry,
  LEGACY_APP_REGISTRY_NAMES
} from './desktop-branding.rules';
import { resolveLaunchPath } from './launch-path';

function getLinuxAutoStartDirectory(): string {
  return path.join(app.getPath('home'), '.config', 'autostart');
}

export function configureDesktopBranding(): void {
  if (!app.isPackaged) {
    return;
  }

  app.setName(DESKTOP_APP_DISPLAY_NAME);

  if (process.platform !== 'darwin') {
    process.title = DESKTOP_APP_DISPLAY_NAME;
  }
}

async function removeLegacyLinuxAutostartEntries(launchPath: string): Promise<void> {
  if (process.platform !== 'linux') {
    return;
  }

  const autostartDirectory = getLinuxAutoStartDirectory();
  const currentLaunchBaseName = path.basename(launchPath);

  let fileNames: string[] = [];

  try {
    fileNames = await fsp.readdir(autostartDirectory);
  } catch {
    return;
  }

  await Promise.all(fileNames.map(async (fileName) => {
    if (!fileName.endsWith('.desktop')) {
      return;
    }

    if (!isLegacyLinuxAutostartEntry(fileName, currentLaunchBaseName)) {
      return;
    }

    await fsp.unlink(path.join(autostartDirectory, fileName)).catch(() => {});
  }));
}

async function disableLegacyWindowsAutoLaunchEntries(launchPath: string): Promise<void> {
  if (process.platform !== 'win32') {
    return;
  }

  await Promise.all(LEGACY_APP_REGISTRY_NAMES.map(async (legacyName) => {
    const launcher = new AutoLaunch({
      name: legacyName,
      path: launchPath
    });

    try {
      if (await launcher.isEnabled()) {
        await launcher.disable();
      }
    } catch {
      // Best-effort cleanup for renamed desktop binaries.
    }
  }));
}

export async function migrateLegacyDesktopBranding(): Promise<void> {
  if (!app.isPackaged) {
    return;
  }

  const launchPath = resolveLaunchPath();

  await removeLegacyLinuxAutostartEntries(launchPath);
  await disableLegacyWindowsAutoLaunchEntries(launchPath);
}
