import 'dart:convert';
import 'dart:io' show Platform;

import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/core/model/livecare/session_status_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class VideoChannel {
  /// channel name
  static const _channel = const MethodChannel("Dr.cloudSolution/videoCall");

  static openVideoCallScreen(
      {kApiKey,
      kSessionId,
      kToken,
      callDuration,
      warningDuration,
      required int vcId,
      required String tokenID,
      required String generalId,
      required int doctorId,
      required String patientName,
      bool isRecording = false,
      required Function() onCallEnd,
      required Function(SessionStatusModel sessionStatusModel) onCallNotRespond,
      required Function(String error) onFailure,
      VoidCallback? onCallConnected,
      VoidCallback? onCallDisconnected}) async {
    onCallConnected = onCallConnected ?? () {};
    onCallDisconnected = onCallDisconnected ?? () {};
    var result;
    try {
      _channel.setMethodCallHandler((call) {
        if (call.method == 'onCallConnected') {
          onCallConnected!();
        }
        if (call.method == 'onCallDisconnected') {
          onCallDisconnected!();
        }
        return true as dynamic;
      });

      result = await _channel.invokeMethod(
        'openVideoCall',
        {
          "kApiKey": kApiKey,
          "kSessionId": kSessionId,
          "kToken": kToken,
          "appLang": "en",
          "baseUrl": BASE_URL_LIVE_CARE,
          "VC_ID": vcId,
          "TokenID": tokenID,
          "generalId": generalId,
          "DoctorId": doctorId,
          "patientName": patientName,
          "isRecording": isRecording,
        },
      );
      if (result['callResponse'] == 'CallEnd') {
        onCallEnd();
      } else {
        SessionStatusModel sessionStatusModel = SessionStatusModel.fromJson(
            Platform.isIOS
                ? result['sessionStatus']
                : json.decode(result['sessionStatus']));
        onCallNotRespond(sessionStatusModel);
      }
    } catch (e) {
      onFailure(e.toString());
    }
  }
}
