// ignore_for_file: unnecessary_overrides

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'package:IQ/app/global/static_informs.dart';
import 'package:url_launcher/url_launcher.dart';

class WifiTestController extends GetxController {
  ///
  final GlobalKey webViewKey = GlobalKey();
  var data = Get.arguments;
  String url1 = "";

  ///
  late PullToRefreshController pullToRefreshController;
  double progress1 = 0;
  onProgressChanged(_, progress2) {
    if (progress2 == 100) {
      pullToRefreshController.endRefreshing();
    }
    progress1 = progress2 / 100;
  }

  onLoadStart(_, url2) {
    url1 = url2.toString();
    update();
  }

  onLoadStop(_, url2) async {
    pullToRefreshController.endRefreshing();
    url1 = url2.toString();
    update();
  }

  onLoadError(_, __, ___, ____) {
    pullToRefreshController.endRefreshing();
  }

  ///
  InAppWebViewController? webViewController;
  onWebViewCreated(controller) {
    webViewController = controller;
  }

  onPressedBack() {
    webViewController?.goBack();
  }

  onPressedForward() {
    webViewController?.goForward();
  }

  onPressedReload() {
    webViewController?.reload();
  }

  ///
  Future<NavigationActionPolicy?> shouldOverrideUrlLoading(_, navAc) async {
    var uri = navAc.request.url!;
    if (!["http", "https", "file", "chrome", "data", "javascript", "about"]
        .contains(uri.scheme)) {
      if (await canLaunchUrl(Uri.parse(url1))) {
        // Launch the App
        await launchUrl(Uri.parse(url1));
        // and cancel the request
        return NavigationActionPolicy.CANCEL;
      }
    }
    return NavigationActionPolicy.ALLOW;
  }

  @override
  void onInit() {
    super.onInit();
    pullToRefreshController = PullToRefreshController(
      options: PullToRefreshOptions(color: brandColor),
      onRefresh: () async {
        if (Platform.isAndroid) {
          webViewController?.reload();
        } else if (Platform.isIOS) {
          webViewController?.loadUrl(
            urlRequest: URLRequest(
              url: await webViewController?.getUrl(),
            ),
          );
        }
      },
    );
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {}
}
