import 'package:mason_logger/mason_logger.dart';
import 'package:yoyo_get_fast_mirror/src/commands/modules/getfastmirro/generate_apt_fast_config_file.dart';
import 'package:yoyo_get_fast_mirror/src/commands/modules/getfastmirro/get_mirro_list.dart';
import 'package:yoyo_get_fast_mirror/src/commands/modules/getfastmirro/network_test.dart';
import 'package:yoyo_get_fast_mirror/src/commands/modules/getfastmirro/test_mirro_speed.dart';
import 'package:yoyo_get_fast_mirror/src/commands/modules/getfastmirro/ubuntu_sources_list_template.dart';
import 'package:yoyo_get_fast_mirror/src/commands/modules/getfastmirro/write_mirror_into_file.dart';
import 'package:yoyo_get_fast_mirror/src/commands/modules/getfastmirro/yoyo_sources_list_template.dart';

final Map<String, dynamic> status = {};
final Logger _logger = Logger();
const List<String> ubuntuMirrorList = [
  'https://mirrors.tuna.tsinghua.edu.cn/ubuntu/',
  'https://mirrors.aliyun.com/ubuntu/',
  'https://repo.huaweicloud.com/ubuntu/'
];

final outputYoyo = lightGreen.wrap('Yoyo Mirrors:');
final outputUbuntu = lightGreen.wrap('Ubuntu Mirrors:');

Future<Map<String, dynamic>> getFastMirror({bool onlyTest = false}) async {
  //首先测试网络链接
  if (!await networkTest()) {
    status['success'] = false;
    status['msg'] = 'NetWork Error';
    return status;
  }
  //获取Yoyo镜像地址
  final yoYoMirrorList = await getMirrorList();
  _logger.info("\n$outputYoyo\n${yoYoMirrorList.join('\n')}\n");
  //测试Yoyo镜像并获取时间和排序后的Map
  final sortedUrlListAndTimeYoyo = await testMirroSpeed(yoYoMirrorList);
  //测试Ubuntu镜像并获取时间和排序后的Map
  _logger.info("\n$outputUbuntu\n${ubuntuMirrorList.join('\n')}\n");
  final sortedUrlListAndTimeUbuntu = await testMirroSpeed(ubuntuMirrorList);
  //生成config
  if (!onlyTest) {
    try {
      generateAptFastConfigFile(
          sortedUrlListAndTimeYoyo, sortedUrlListAndTimeUbuntu,);
    } catch (e) {
      status['success'] = false;
      status['msg'] = 'Generate Config File Error';
      return status;
    } finally {
      status['success'] = true;
    }
    //写入镜像源文件
    //Yoyo
    final fastestYoyoMirror =
        sortedUrlListAndTimeYoyo.first.entries.first.value;
    final yoyoSourcesListFile = yoyoSourcesListTemplate(fastestYoyoMirror);
    writeMirrorIntoFile(
      yoyoSourcesListFile,
      '/etc/apt/sources.list.d/yoyo-os.list',
    );
    //Ubuntu
    final fastestUbuntuMirror =
        sortedUrlListAndTimeUbuntu.first.entries.first.value;
    final ubuntuSourcesLIstFile =
        ubuntuSourcesListTemplate(fastestUbuntuMirror);
    writeMirrorIntoFile(
      ubuntuSourcesLIstFile,
      '/etc/apt/sources.list',
    );
  }
  //返回执行结果
  return status;
}
