import 'dart:async';
import 'package:flutter/material.dart';

import 'package:imagini/core/imagini_application.dart';
import 'package:imagini/api/imagini_api_repository.dart';
import 'package:imagini/graphql/imagini_graphql.dart';

class HomeBloc{

  final ImaginiApplication _application;
  ImaginiAPIRepository _imaginiAPI;

  final _mediaItemsController = StreamController<MediaItems$Query>.broadcast();
  Stream<MediaItems$Query> get mediaItemsResult => _mediaItemsController.stream;

  final _loginController = StreamController<bool>.broadcast();
  Stream<bool> get loginResult => _loginController.stream;

  final _authenticatedController = StreamController<bool>.broadcast();
  Stream<bool> get authenticatedResult => _authenticatedController.stream;

  HomeBloc(this._application){
    _init();
  }

  void _init(){
    _imaginiAPI = _application.imaginiAPI;
    getMediaItems();
  }

  void dispose(){
    _loginController.close();
    _authenticatedController.close();
    _mediaItemsController.close();
  }

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

  getMediaItems(){
    _mediaItemsController.addStream(_imaginiAPI.mediaItems());
  }

  checkAuthentication(){
    _authenticatedController.addStream(_imaginiAPI.isAuthenticated());
  }

  attemptHome(String username, password, server){
    _loginController.addStream(_imaginiAPI.login(username, password, server));
  }
}
