import { dialog } from 'electron';
import path from 'path';
import { createWriteStream } from 'fs-extra';
import { container } from '../../core/container';
import { II18nTranslator } from '../i18n/i-i18n-translator';
import { answer } from '../ipc/annotations/answer';
import { INhentaiApi } from './i-nhentai-api';
import { IFavorite } from './nhentai';

export class NhentaiIpcController implements IIpcController {
  private readonly nhentaiApi: INhentaiApi;

  private readonly translator: II18nTranslator;

  private constructor(nhentaiApi: INhentaiApi, translator: II18nTranslator) {
    this.nhentaiApi = nhentaiApi;
    this.translator = translator;
  }

  @answer(IpcChannel.NHENTAI_SAVE_FAVORITES)
  public async nhentaiSaveFavorites(): Promise<void> {
    const result = await dialog.showOpenDialog({
      properties: ['openDirectory'],
      title: this.translator.t('Select torrent file save location'),
    });

    const favoritesStream = await this.nhentaiApi.getFavorites();

    return new Promise((resolve) => {
      favoritesStream.on('data', (favorite: IFavorite) => {
        const writable = createWriteStream(path.resolve(result.filePaths[0], favorite.name));
        favorite.torrentFile.pipe(writable);
      });

      favoritesStream.once('close', resolve);
    });
  }

  public get(): NhentaiIpcController {
    const nhentaiApi: INhentaiApi = container.get('nhentai-api');
    const translator: II18nTranslator = container.get('i18n-translator');
    return new NhentaiIpcController(nhentaiApi, translator);
  }
}
