import 'package:electronic_assistant/base/base_controller.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';

class BrowserController extends BaseController {
  String url = (Get.arguments is String) ? (Get.arguments as String) : '';

  final WebViewController webViewController = WebViewController();

  final title = ''.obs;

  @override
  void onInit() {
    super.onInit();
    webViewController.setNavigationDelegate(
      NavigationDelegate(
        onPageFinished: (String url) {
          webViewController.getTitle().then((title) {
            if (title != null) {
              this.title.value = title;
            }
          });
        },
        onNavigationRequest: (NavigationRequest request) {
          return NavigationDecision.navigate;
        },
      ),
    );
    webViewController.setJavaScriptMode(JavaScriptMode.unrestricted);
  }

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

  void loadUrl() {
    if (url.isEmpty) {
      return;
    }
    webViewController.loadRequest(Uri.parse(url));
  }

  Future<bool> handleBack() async {
    if (await webViewController.canGoBack()) {
      webViewController.goBack();
      return false;
    }
    return true;
  }
}
