import 'dart:async';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

import 'package:mobdr/service/shared_prefs.dart';
import 'package:mobdr/main.dart';
import 'package:mobdr/events.dart';

class TabMP4Page extends StatefulWidget {
  @override
  _TabMP4PageState createState() => _TabMP4PageState();
}

class _TabMP4PageState extends State<TabMP4Page>
    with AutomaticKeepAliveClientMixin {
  late final WebViewController controller;
  late StreamSubscription sub;

  int loadingPercentage = 0;
  String url = SharedPrefs().urlMP4;

  @override
  void initState() {
    super.initState();

    controller = WebViewController()
      ..setNavigationDelegate(NavigationDelegate(
        onPageStarted: (url) {
          setState(() {
            loadingPercentage = 0;
          });
        },
        onProgress: (progress) {
          setState(() {
            loadingPercentage = progress;
          });
        },
        onPageFinished: (url) {
          setState(() {
            loadingPercentage = 100;
          });
        },
      ))
      ..loadRequest(
        Uri.parse(url),
      );

    sub = eventBus.on<UrlEvent>().listen((e) {
      setState(() {
        controller.loadRequest(
          Uri.parse(e.url),
        );
      });
    });
  }

  @override
  void dispose() {
    sub.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SafeArea(
      child: Stack(
        children: [
          WebViewWidget(
            controller: controller,
          ),
          if (loadingPercentage < 100)
            LinearProgressIndicator(
              value: loadingPercentage / 100.0,
            ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
