import 'package:diplomaticquarterapp/pages/conference/draggable_publisher.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';

import 'OpenTokPlatformBridge.dart';


class OpenTokConnectCallPage extends  StatefulWidget{
  final String sessionId;
  final String token;
  final String apiKey;
  OpenTokConnectCallPage({@required this.sessionId, @required this.token, @required this.apiKey});
  
  @override
  State<StatefulWidget> createState() => OpenTokState();
  
}

class OpenTokState extends State<OpenTokConnectCallPage>{
  OpenTokPlatformBridge openTokPlatform;
  OpenTokSDKState sdkState = OpenTokSDKState.LOGGED_OUT;

  initOpenTok(){
    openTokPlatform = OpenTokPlatformBridge.init(
        apiKey: widget.apiKey,
        sessionID: widget.sessionId,
        token: widget.token,
        onStateChange: (state) {
          setState(() => sdkState = state);
        }
    );
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        actions: [
          TextButton(onPressed: (){
            initOpenTok();
          }, child: Icon(Icons.connect_without_contact_outlined, color: Colors.green,))
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: Stack(
              children: [
                if(sdkState == OpenTokSDKState.LOGGED_IN)
                  ...platformVideoViews(),


                if(sdkState == OpenTokSDKState.LOGGED_OUT)
                  Center(child: Text("Logged Out"),),

                if(sdkState == OpenTokSDKState.ERROR)
                  Center(child: Text("Error opening session"),),

                if(sdkState == OpenTokSDKState.WAIT)
                  Center(child: CircularProgressIndicator(),),

                if(sdkState == OpenTokSDKState.ON_CALL)
                  Container(),
              ],
            ),
          ),
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                    child: Text('Mute Video') ,onPressed: () => openTokPlatform.toggleVideo()
                ),
              ),
              SizedBox(width: 20,),
              Expanded(
                child: ElevatedButton(
                    child: Text('Mute Audio') ,onPressed: () => openTokPlatform.toggleAudio()
                ),
              ),
              SizedBox(width: 20,),
              Expanded(
                child: ElevatedButton(
                    child: Text('Change Camera') ,onPressed: () => openTokPlatform.swapCamera()
                ),
              ),
            ],
          )
        ],
      ),
    );
  }

  bool remoteVideoOnFull = true;
  List<Widget> platformVideoViews(){
    return [
      SizedBox(
          width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height,
          child: remoteVideoOnFull ? remotePlatformVideoView() : localPlatformVideoView()
      ),

      DraggablePublisher(
        onButtonBarHeight: ((double)async*{}(50)),
        onButtonBarVisible: ((bool)async*{}(true)),
        availableScreenSize: MediaQuery.of(context).size,
        child: InkWell(
          child: (remoteVideoOnFull ? localPlatformVideoView() : remotePlatformVideoView()),
          onTap: (){
            print('');
          },
        ),
      )
    ];
  }

  Widget localPlatformVideoView(){
    return PlatformViewLink(
        viewType: 'local-video-container', // custom platform-view-type
        surfaceFactory:
            (BuildContext context, PlatformViewController controller) {
          return AndroidViewSurface(
            controller: controller,
            gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{},
            hitTestBehavior: PlatformViewHitTestBehavior.opaque,
          );
        },

        onCreatePlatformView: (PlatformViewCreationParams params) {
          return PlatformViewsService.initSurfaceAndroidView(
            id: params.id,
            viewType: 'local-video-container',
            // custom platform-view-type,
            layoutDirection: TextDirection.ltr,
            creationParams: {},
            creationParamsCodec: StandardMessageCodec(),
          )
            ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)
            ..create();
        },
      );
  }

  Widget remotePlatformVideoView(){
    return PlatformViewLink(
        viewType: 'remote-video-container', // custom platform-view-type
        surfaceFactory:
            (BuildContext context, PlatformViewController controller) {
          return AndroidViewSurface(
            controller: controller,
            gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{},
            hitTestBehavior: PlatformViewHitTestBehavior.opaque,
          );
        },
        onCreatePlatformView: (PlatformViewCreationParams params) {
          return PlatformViewsService.initSurfaceAndroidView(
            id: params.id,
            viewType: 'remote-video-container',
            // custom platform-view-type,
            layoutDirection: TextDirection.ltr,
            creationParams: {},
            creationParamsCodec: StandardMessageCodec(),
          )
            ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)
            ..create();
        },
      );
  }
  
}