/*
 * @Author: ,: XianKaiQun
 * @Date: ,: 2020-09-23 18:39:13
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-07-20 17:26:55
 * @Description: ,: 
 */
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:wisdom_cli/src/extensions/adapt.dart';
import 'package:wisdom_cli/src/widgets/text.dart';

import '../../new/widgets/app_bar.dart';
import '../../new/widgets/empty_widget.dart';
import '../../new/widgets/theme.dart';
// import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class WisWebView extends StatefulWidget {
  WisWebView({Key? key, this.initialUrl}) : super(key: key);
  final String? initialUrl;
  @override
  _WisWebViewState createState() => _WisWebViewState();
}

class _WisWebViewState extends State<WisWebView> {
  String? title;
  final GlobalKey webViewKey = GlobalKey();

  // 1
  late WebViewController controller;
  @override
  void initState() {
    // 2
    if (widget.initialUrl != null && widget.initialUrl != '') {
      controller = WebViewController()
        ..setJavaScriptMode(JavaScriptMode.unrestricted)
        ..setNavigationDelegate(
          NavigationDelegate(
            //calling the function which fetches the title as soon as the page loads
            onPageFinished: (url) {
              setAppBarTitle();
            },
          ),
        )
        ..loadRequest(Uri.parse(widget.initialUrl ?? ''));
    }

    super.initState();
  }

  setAppBarTitle() async {
    title = await controller.getTitle();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = WTheme.of(context).colorScheme;

    return Scaffold(
      appBar: WAppBar(
        brightness: Brightness.light,
        iconTheme: IconThemeData(
          color: colorScheme.mainTitle,
          size: 19.pt,
        ),
        backgroundColor: Colors.white,
        title: WisText(title ?? '',
            size: 19.pt, weight: FontWeight.w600, color: colorScheme.mainTitle),
      ),
      body: widget.initialUrl != null && widget.initialUrl != ''
          ? WebViewWidget(
              controller: controller,
            )
          : WEmptyWidget(),
    );
  }
}
