import 'dart:async';
import 'dart:convert';
import 'dart:core';
import 'package:built_collection/built_collection.dart';
import 'package:invoiceninja_flutter/constants.dart';
import 'package:invoiceninja_flutter/data/models/serializers.dart';
import 'package:invoiceninja_flutter/redux/auth/auth_state.dart';
import 'package:invoiceninja_flutter/data/models/models.dart';
import 'package:invoiceninja_flutter/data/web_client.dart';

class StubRepository {

  const StubRepository({
    this.webClient = const WebClient(),
  });

  final WebClient webClient;

  Future<StubEntity> loadItem(
      CompanyEntity company, AuthState auth, int entityId) async {
    final dynamic response = await webClient.get(
        '${auth.url}/stubs/$entityId', company.token);

    final StubItemResponse stubResponse =
        serializers.deserializeWith(StubItemResponse.serializer, response);

    return stubResponse.data;
  }

  Future<BuiltList<StubEntity>> loadList(
      CompanyEntity company, AuthState auth, int updatedAt) async {
    String url = auth.url + '/stubs?';

    if (updatedAt > 0) {
      url += '&updated_at=${updatedAt - kUpdatedAtBufferSeconds}';
    }

    final dynamic response = await webClient.get(url, company.token);

    final StubListResponse stubResponse =
        serializers.deserializeWith(StubListResponse.serializer, response);

    return stubResponse.data;
  }
  
  Future<StubEntity> saveData(
      CompanyEntity company, AuthState auth, StubEntity stub,
      [EntityAction action]) async {
    final data = serializers.serializeWith(StubEntity.serializer, stub);
    dynamic response;

    if (stub.isNew) {
      response = await webClient.post(
          auth.url + '/stubs',
          company.token,
          json.encode(data));
    } else {
      var url = auth.url + '/stubs/' + stub.id.toString();
      if (action != null) {
        url += '?action=' + action.toString();
      }
      response = await webClient.put(url, company.token, json.encode(data));
    }

    final StubItemResponse stubResponse =
    serializers.deserializeWith(StubItemResponse.serializer, response);

    return stubResponse.data;
  }
}
