import 'dart:async';
import 'package:docuframe/docuframe.dart' as df;
import 'package:hl_lieferservice/util.dart';
import 'package:flutter/cupertino.dart';

class LocalDocuFrameConfiguration {
  String host;
  String backendUrl;
  final String user;
  final String pass;
  final List<String> appNames;
  final String appKey;

  LocalDocuFrameConfiguration(
      {required this.host,
      required this.appKey,
      required this.appNames,
      required this.pass,
        required this.backendUrl,
      required this.user});

  Map<String, dynamic> toJson() {
    return {
      "host": host,
      "user": user,
      "pass": pass,
      "backendUrl": backendUrl,
      "appNames": appNames,
      "appKey": appKey
    };
  }

  factory LocalDocuFrameConfiguration.fromJson(Map<String, dynamic> json) {
    return LocalDocuFrameConfiguration(
        host: getValueOrThrowIfNotPresent("host", json),
        appKey: getValueOrThrowIfNotPresent("appKey", json),
        appNames: (getValueOrThrowIfNotPresent("appNames", json) as List)
            .cast<String>(),
        pass: getValueOrThrowIfNotPresent("pass", json),
        backendUrl: getValueOrThrowIfNotPresent("backendUrl", json),
        user: getValueOrThrowIfNotPresent("user", json));
  }
}

class ErpFrameService {
  ErpFrameService({required this.config});

  final LocalDocuFrameConfiguration config;

  df.DocuFrameConfiguration get dfConfig {
    df.DocuFrameConfiguration dfConfig =
        df.DocuFrameConfiguration(url: config.host, appkey: config.appKey);

    return dfConfig;
  }

  Future<df.LoginSession> getSession() async {
    df.LoginV1 request = df.LoginV1(config: dfConfig);
    df.LoginSession session =
        await request.authorize(config.user, config.pass, config.appNames);

    debugPrint("LOGIN WITH SESSION ID ${session.sessionId}");

    return session;
  }

  Future<void> logout(df.LoginSession? session) async {
    if (session != null) {
      try {
        await df.Logout(config: dfConfig, session: session).logout();
      } catch (e, st) {
        debugPrint("Logout failed");
        debugPrint(e.toString());
        debugPrint(st.toString());
      }
      debugPrint("Logged out with session ID: ${session.sessionId}");
    }
  }
}