
import 'package:flutter/Material.dart';
import 'package:get/get.dart';
import '../../base/base_controller.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();
    _initWebSetting();
  }

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

  void _initWebSetting() {
    webViewController.setJavaScriptMode(JavaScriptMode.unrestricted);
    webViewController.setBackgroundColor(Colors.white);
    webViewController.setNavigationDelegate(
      NavigationDelegate(
        onPageFinished: (String url) {
          _getTitle();
        },
      ),
    );
  }

  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;
  }

  void _getTitle() async {
    await Future.delayed(const Duration(milliseconds: 500));
    webViewController.getTitle().then((title) {
      if (title != null) {
        this.title.value = title;
      }
    });
  }
}
