import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'package:jubo/model/person.dart';
import 'package:jubo/util/params.dart';
import 'dart:convert';
import 'dart:io';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:jubo/control/genericService.dart' as generic;

class PersonService {
  Future<SharedPreferences> _storage() {
    return SharedPreferences.getInstance();
  }

  Future<void> postPerson(ModelPerson person, File image) async {
    try {
      String json;
      String method = "/ws_jubo/service/v1/person";
      if (person.id != null) {
        json = person.toJson();
      } else {
        json = person.toJsonNew();
      }

      /*
      StreamedResponse stream =
          await generic.requestPostFormData(json, image, method, "");

      http.Response result =
          await http.Response.fromStream(stream).then((response) {
        return response;
      });

       */

      http.Response result = await generic.requestPostFormData(json, image, method, "");

      Map<String, dynamic> body;

      body = jsonDecode(result.body);

      //print(result.statusCode);
      //print(result.body);
      if (result.statusCode != 200 || body['error'] == true) {
        throw 'Falha de comunicação';
      }

      //m = jsonResponse.map((job) => new ModelPerson.fromJson(job));
      final m = new ModelPerson.fromJson(body['data']);
      final prefs = await _storage();

      prefs.setBool('_rememberMe', true);
      prefs.setString('_person', m.toJson());
    } catch (e) {
      throw e;
    }
  }

  Future<bool> forgotPass(String email) async {
    try {
      String method = "/ws_jubo/service/v1/auth_forgot";

      http.Response result =
          await generic.requestPost({'email': email}, method, "");

      Map<String, dynamic> body = jsonDecode(result.body);

      print(result.statusCode);
      print(result.body);

      if (result.statusCode != 200 || body['error'] == true) {
        //throw 'Falha de comunicação';
        return false;
      } else {
        return true;
      }
    } catch (e) {
      return false;
      throw e;
    }
  }

  Future<void> changePassword(int id,String password,String newPassword) async {
    try {
      dynamic js;
      String method = "/ws_jubo/service/v1/person/pass";

      js = {'id': id,'password': password,'newPassword': newPassword};


      http.Response result = await generic.requestPut(js, method, "");

      Map<String, dynamic> body;

      body = jsonDecode(result.body);

      //print(result.statusCode);
      //print(result.body);
      if (result.statusCode != 200 ) {

        throw 'Falha de comunicação';
      }
      if (body['error'] == true) {
        throw 'Falha de comunicação';
      }

      //m = jsonResponse.map((job) => new ModelPerson.fromJson(job));
      final m = new ModelPerson.fromJson(body['data']);
      final prefs = await _storage();

      prefs.setString('_person', m.toJson());
    } catch (e) {
      print(e);
      throw e;
    }
  }

  /*
  Future<String> getCompanyKey() async {
    final prefs = await _storage();
    return prefs.getString(_keyStore);
  }*/

  Future<ModelPerson> getPerson() async {
    ModelPerson m;
    final prefs = await _storage();
    return new ModelPerson.fromJson(jsonDecode(prefs.get('_person')));
  }

  Future<bool> isAuth() async {
    final prefs = await _storage();
    return prefs.containsKey('_rememberMe') && prefs.containsKey('_person');
  }

  Future<Image> getPhoto() async {
    ModelPerson m = await getPerson();
    return Image.network(
        "$urlPrincipal/ws_jubo/service/v1/person/photo/${m.id}");
  }

  Future<void> logout() async {
    final prefs = await _storage();
    prefs.remove('_person');
    prefs.remove('_rememberMe');
  }
}
