// ignore_for_file: depend_on_referenced_packages

import 'dart:core';
import 'package:path/path.dart' as path;
import 'package:oto/oto/application.dart';
import 'package:oto/oto/commands/command.dart';
import 'package:oto/oto/data/command_data.dart';
import 'package:oto/oto/commands/ftp/ftp.dart';

class Download extends Command {
  @override
  Future execute(DataCommand command) async {
    var data = DataFTP.fromJson(getParam(command));

    //Check asterisk
    var downloadMap = <String, String>{};
    var map = data.map;
    int port = data.port == 0 ? (data.sftp ? 22 : 21) : data.port;

    var ftp = data.sftp
        ? SFTP(data.host,
            port: port,
            user: data.user,
            password: data.password,
            runtime: runtime)
        : FTP(data.host, port: port, user: data.user, password: data.password);
    Application.log(
        '========================= [Try connection] =========================');
    await ftp.connect();
    Application.log(
        '========================= [Connected! Start Download] ================');
    var entries = map.entries;
    for (var entry in entries) {
      var local = path.join(workspace, entry.key);
      var remote = entry.value;
      Application.log('[Download]: $local ====> $remote');

      downloadMap[remote] = local;
    }

    if (downloadMap.isNotEmpty) await ftp.download(downloadMap);

    await ftp.disconnect();
    Application.log(
        '========================= [Download completed!] ====================');
    return complete(0, command);
  }
}

void registerFtpDownloadCommand() {
  Command.register(
    CommandType.Download,
    () => Download(),
    spec: const CommandSpec(
      type: CommandType.Download,
      category: 'ftp',
      dataModel: 'DataFTP',
      samplePath: 'assets/yaml/sample/09_network.yaml',
    ),
  );
}
