import 'dart:async';
import 'package:imagini/api/api_provider.dart';
import 'package:imagini/graphql/imagini_graphql.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:flutter/material.dart';

class ImaginiAPIRepository {
  APIProvider _apiProvider;

  ImaginiAPIRepository(this._apiProvider);

  Stream<bool> login(String user, password, server) {
    return Stream.fromFuture(_apiProvider.login(user, password, server).then((QueryResult resp) {
      if (resp.exception != null)
        return false;

      final loginResponse = Login$Query.fromJson(resp.data);
      if (loginResponse.login.result == AuthResult.failure)
        return false;

      return true;
    }));
  }

  Stream<QueryResult> me() {
    return Stream.fromFuture(_apiProvider.me());
  }

  Stream<MediaItems$Query> mediaItems() {
    return Stream.fromFuture(_apiProvider.mediaItems().then((QueryResult resp) {
      final mediaItemsResponse = MediaItems$Query.fromJson(resp.data);
      return mediaItemsResponse;
    }));
  }

  Stream<bool> isAuthenticated() {
    return Stream.fromFuture(_apiProvider.me().then((QueryResult resp) {
      if (resp.exception != null)
        return false;
      return true;
    }));
  }

  Image getImage(String fileName) {
    return _apiProvider.getImage(fileName);
  }
}
