import 'package:built_collection/built_collection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:invoiceninja_flutter/data/models/models.dart';
import 'package:invoiceninja_flutter/redux/app/app_state.dart';
import 'package:invoiceninja_flutter/redux/stub/stub_actions.dart';
import 'package:invoiceninja_flutter/redux/stub/stub_selectors.dart';
import 'package:redux/redux.dart';

import 'stub_screen.dart';

class StubScreenBuilder extends StatelessWidget {
  const StubScreenBuilder({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, StubScreenVM>(
      converter: StubScreenVM.fromStore,
      builder: (context, vm) {
        return StubScreen(
          viewModel: vm,
        );
      },
    );
  }
}

class StubScreenVM {
  StubScreenVM({
    @required this.isInMultiselect,
    @required this.stubList,
    @required this.userCompany,
    @required this.onEntityAction,
    @required this.stubMap,
  });

  final bool isInMultiselect;
  final UserCompanyEntity userCompany;
  final List<String> stubList;
  final Function(BuildContext, List<BaseEntity>, EntityAction) onEntityAction;
  final BuiltMap<String, StubEntity> stubMap;

  static StubScreenVM fromStore(Store<AppState> store) {
    final state = store.state;

    return StubScreenVM(
      stubMap: state.stubState.map,
      stubList: memoizedFilteredStubList(state.stubState.map,
          state.stubState.list, state.stubListState),
      userCompany: state.userCompany,
      isInMultiselect: state.stubListState.isInMultiselect(),
      onEntityAction: (BuildContext context, List<BaseEntity> stubs,
              EntityAction action) =>
          handleStubAction(context, stubs, action),
    );
  }
}
