import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/header.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/url.dart';
import 'package:webview_flutter/webview_flutter.dart';

class AnswerQuestionResultWebView extends StatefulWidget {
  final RQId;
  AnswerQuestionResultWebView(this.RQId);

  @override
  _AnswerQuestionResultWebViewState createState() =>
      _AnswerQuestionResultWebViewState(this.RQId);
}

class _AnswerQuestionResultWebViewState
    extends State<AnswerQuestionResultWebView> {
  final Completer<WebViewController> _webviewController =
      Completer<WebViewController>();
  var RQId;
  var urlMain = AppUrl.Questionnaire_Result + "?id={RQId}"+"&authenKey="+AppUrl.AuthenKey;
  bool isLoading = false;

  _AnswerQuestionResultWebViewState(this.RQId);

  @override
  void initState() {
    super.initState();
    print("answer_question_result_web_view.dart 1");
    setState(() {
      isLoading = true;
    });
    wait();
  }

  wait() async {
    await Future.delayed(const Duration(milliseconds: 2000));
    setState(() {
      isLoading = false;
    });
  }

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

  JavascriptChannel _saveFinnishJavascriptChannel(BuildContext context) {
    print('AnswerQuestionResultWebView : _saveFinnishJavascriptChannel');
    return JavascriptChannel(
        name: 'saveFinnish',
        onMessageReceived: (message) {
          Navigator.pop(context);
        });
  }

  _bulidWebView3() {
    setState(() {
      urlMain = Uri.encodeFull(urlMain.replaceAll("{RQId}", RQId));
      print(urlMain);
    });
    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height - 175,
      margin: EdgeInsets.only(
        top: mediaQuery(context, 'h', 338),
      ),
      child: WebView(
        initialUrl: urlMain,
        javascriptMode: JavascriptMode.unrestricted,
        javascriptChannels: <JavascriptChannel>[
          _saveFinnishJavascriptChannel(context),
        ].toSet(),
        onWebViewCreated: (WebViewController webViewController) {
          _webviewController.complete(webViewController);
        },
        onPageStarted: (url) {},
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }

    return Material(
      color: AppColors.bgColor,
      child: Stack(
        children: <Widget>[
          Header.mainMenu(context),
          _bulidWebView3(),
          Header.header2(context),
        ],
      ),
    );
  }
}
