import 'dart:async';
import 'dart:io';
import 'dart:ui';


import 'package:bot_toast/bot_toast.dart';
import 'package:dart_json_mapper/dart_json_mapper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'package:kommon/tool/sp_util.dart';
import 'package:naiyouwl/app/controller/dialog.dart';
import 'package:naiyouwl/app/i18n/i18n.dart';
import 'package:naiyouwl/app/controller/GlobalController.dart';
import 'package:naiyouwl/app/controller/config.dart';
import 'package:naiyouwl/app/controller/controllers.dart';
import 'package:naiyouwl/app/controller/core.dart';
import 'package:naiyouwl/app/controller/service.dart';
import 'package:naiyouwl/app/controller/tray.dart';
import 'package:naiyouwl/app/controller/window.dart';
import 'package:proxy_manager/proxy_manager.dart';
import 'package:window_manager/window_manager.dart';


import 'app/routes/app_pages.dart';
import 'main.mapper.g.dart' show initializeJsonMapper;

final proxyManager = ProxyManager();
final isDesktop = GetPlatform.isDesktop;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (isDesktop) {
    await Future.wait([
      Future.microtask(() async {
        await windowManager.ensureInitialized();
        await windowManager.setPreventClose(true);
      })
    ]);
  }
  initializeJsonMapper();
  JsonMapper().useAdapter(JsonMapperAdapter(valueDecorators: {
    typeOf<Map<String, String>>(): (value) {
      return Map.castFrom<dynamic, dynamic, String, String>(value);
    },
  }));





  Get.put(TrayController());
  Get.put(WindowController());
  Get.put(CoreController());
  Get.put(ConfigController());
  Get.put(ServiceController());
  Get.put(GlobalController());
  Get.put(DialogController());

  await initAppService();

  runApp(
      const MyApp()
  );

  if (isDesktop) {
    initWindow();
  }

}

Future<void> initWindow() async {
  const width = 375.0;
  const height = 736.0;

  WindowOptions opts = const WindowOptions(
    minimumSize: Size(width, height),
    maximumSize: Size(width, height - kToolbarHeight),
    size: Size(width, height),
    center: true,
    backgroundColor: Colors.transparent,
    skipTaskbar: true,
    titleBarStyle: TitleBarStyle.hidden,
  );
  windowManager.waitUntilReadyToShow(opts, () {
    // hide window when start
    // if (Get.find<ClashService>().isHideWindowWhenStart() && kReleaseMode) {
    //   windowManager.hide();
    // } else {
    //   windowManager.show();
    //   windowManager.focus();
    // }

    windowManager.show();
    windowManager.focus();
    //windowManager.show();
    // windowManager.focus();
  });
}


Future<void> initAppService() async {
  await SpUtil.getInstance();
  // var ach = await MethodChannel('app.channel.shared.data');
  // if (ach == "arm64"){
  //
  // } else {
  //
  // }
}
class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late StreamSubscription<bool> listenShow;

  @override
  void initState() {
    controllers.init();
    controllers.global.init(context);
    listenShow = controllers.window.isVisible.stream.listen((event) async {
      if (!event) return;
      await Future.delayed(const Duration(milliseconds: 100));
      await Get.forceAppUpdate();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    const Set<PointerDeviceKind> kTouchLikeDeviceTypes = <PointerDeviceKind>{
      PointerDeviceKind.touch,
      PointerDeviceKind.mouse,
      PointerDeviceKind.stylus,
      PointerDeviceKind.invertedStylus,
      PointerDeviceKind.unknown
    };


    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      scrollBehavior: const MaterialScrollBehavior().copyWith(
          scrollbars: true,
          dragDevices: kTouchLikeDeviceTypes
      ),
      translations: I18n(),
      locale: Get.deviceLocale,
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: I18n.locales,
      builder: BotToastInit(),
      title: "Application",
      initialRoute: AppPages.INITIAL,
      getPages: AppPages.routes,

    );
  }

  @override
  void dispose() {
    controllers.global.dispose();
    listenShow.cancel();
    super.dispose();
  }
}