import 'dart:async';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import 'package:built_collection/built_collection.dart';
import 'package:invoiceninja_flutter/redux/ui/entity_ui_state.dart';
import 'package:invoiceninja_flutter/redux/ui/list_ui_state.dart';
import 'package:invoiceninja_flutter/data/models/models.dart';
import 'package:invoiceninja_flutter/redux/ui/pref_state.dart';

part 'stub_state.g.dart';

abstract class StubState implements Built<StubState, StubStateBuilder> {

  factory StubState() {
    return _$StubState._(
      map: BuiltMap<String, StubEntity>(),
      list: BuiltList<String>(),
    );
  }
  StubState._();

  @override
  @memoized
  int get hashCode;

  BuiltMap<String, StubEntity> get map;
  BuiltList<String> get list;

  StubEntity get(String stubId) {
    if (map.containsKey(stubId)) {
      return map[stubId];
    } else {
      return StubEntity(id: stubId);
    }
  }

  StubState loadStubs(BuiltList<StubEntity> clients) {
    final map = Map<String, StubEntity>.fromIterable(
      clients,
      key: (dynamic item) => item.id,
      value: (dynamic item) => item,
    );

    return rebuild((b) => b
      ..map.addAll(map)
      ..list.replace((map.keys.toList() + list.toList()).toSet().toList()));
  }


  static Serializer<StubState> get serializer => _$stubStateSerializer;
}

abstract class StubUIState extends Object with EntityUIState implements Built<StubUIState, StubUIStateBuilder> {

  factory StubUIState(PrefStateSortField sortField) {
    return _$StubUIState._(
      listUIState: ListUIState(sortField?.field ?? StubFields.name, sortAscending: sortField?.ascending),
      editing: StubEntity(),
      selectedId: '',
      tabIndex: 0,
    );
  }
  StubUIState._();

  @override
@memoized
  int get hashCode;

  @nullable
  StubEntity get editing;

  @override
  bool get isCreatingNew => editing.isNew;

  @override
  String get editingId => editing.id;

  static Serializer<StubUIState> get serializer => _$stubUIStateSerializer;
}