import 'package:redux/redux.dart';
import 'package:built_collection/built_collection.dart';
import 'package:invoiceninja_flutter/redux/app/app_actions.dart';
import 'package:invoiceninja_flutter/data/models/models.dart';
import 'package:invoiceninja_flutter/redux/company/company_actions.dart';
import 'package:invoiceninja_flutter/redux/ui/entity_ui_state.dart';
import 'package:invoiceninja_flutter/redux/stub/stub_actions.dart';
import 'package:invoiceninja_flutter/redux/ui/list_ui_state.dart';
import 'package:invoiceninja_flutter/redux/stub/stub_actions.dart';
import 'package:invoiceninja_flutter/redux/stub/stub_state.dart';
import 'package:invoiceninja_flutter/data/models/entities.dart';

EntityUIState stubUIReducer(StubUIState state, dynamic action) {
  return state.rebuild((b) => b
    ..listUIState.replace(stubListReducer(state.listUIState, action))
    ..editing.replace(editingReducer(state.editing, action))
    ..selectedId = selectedIdReducer(state.selectedId, action));
}

Reducer<String> selectedIdReducer = combineReducers([
  TypedReducer<String, ViewStub>(
      (String selectedId, dynamic action) => action.stubId),
  TypedReducer<String, AddStubSuccess>(
      (String selectedId, dynamic action) => action.stub.id),
  TypedReducer<String, SelectCompany>((selectedId, action) => ''),
]);

final editingReducer = combineReducers<StubEntity>([
  TypedReducer<StubEntity, SaveStubSuccess>(_updateEditing),
  TypedReducer<StubEntity, AddStubSuccess>(_updateEditing),
  TypedReducer<StubEntity, RestoreStubsSuccess>((stubs, action) {
                                                   return action.stubs[0];
                                                 }),
  TypedReducer<StubEntity, ArchiveStubsSuccess>((stubs, action) {
                                                  return action.stubs[0];
                                                }),
  TypedReducer<StubEntity, DeleteStubsSuccess>((stubs, action) {
                                                 return action.stubs[0];
                                               }),
  TypedReducer<StubEntity, EditStub>(_updateEditing),
  TypedReducer<StubEntity, UpdateStub>((stub, action) {
   return action.stub.rebuild((b) => b..isChanged = true);
 }),
  TypedReducer<StubEntity, SelectCompany>(_clearEditing),
  TypedReducer<StubEntity, DiscardChanges>(_clearEditing),
]);

StubEntity _clearEditing(StubEntity stub, dynamic action) {
  return StubEntity();
}

StubEntity _updateEditing(StubEntity stub, dynamic action) {
  return action.stub;
}


final stubListReducer = combineReducers<ListUIState>([
  TypedReducer<ListUIState, SortStubs>(_sortStubs),
  TypedReducer<ListUIState, FilterStubsByState>(_filterStubsByState),
  TypedReducer<ListUIState, FilterStubs>(_filterStubs),
  TypedReducer<ListUIState, FilterStubsByCustom1>(_filterStubsByCustom1),
  TypedReducer<ListUIState, FilterStubsByCustom2>(_filterStubsByCustom2),
  TypedReducer<ListUIState, FilterStubsByEntity>(_filterStubsByClient),
  TypedReducer<ListUIState, StartStubMultiselect>(_startListMultiselect),
  TypedReducer<ListUIState, AddToStubMultiselect>(_addToListMultiselect),
  TypedReducer<ListUIState, RemoveFromStubMultiselect>(
      _removeFromListMultiselect),
  TypedReducer<ListUIState, ClearStubMultiselect>(_clearListMultiselect),
    TypedReducer<ListUIState, ClearEntityFilter>(
        (state, action) => state.rebuild((b) => b
          ..filterEntityId = null
          ..filterEntityType = null)),

]);

ListUIState _filterStubsByClient(
    ListUIState stubListState, FilterStubsByEntity action) {
  return stubListState.rebuild((b) => b
  ..filterEntityId = action.entityId
  ..filterEntityType = action.entityType);
}

ListUIState _filterStubsByCustom1(
    ListUIState stubListState, FilterStubsByCustom1 action) {
  if (stubListState.custom1Filters.contains(action.value)) {
    return stubListState
        .rebuild((b) => b..custom1Filters.remove(action.value));
  } else {
    return stubListState.rebuild((b) => b..custom1Filters.add(action.value));
  }
}

ListUIState _filterStubsByCustom2(
    ListUIState stubListState, FilterStubsByCustom2 action) {
  if (stubListState.custom2Filters.contains(action.value)) {
    return stubListState
        .rebuild((b) => b..custom2Filters.remove(action.value));
  } else {
    return stubListState.rebuild((b) => b..custom2Filters.add(action.value));
  }
}

ListUIState _filterStubsByState(
    ListUIState stubListState, FilterStubsByState action) {
  if (stubListState.stateFilters.contains(action.state)) {
    return stubListState.rebuild((b) => b..stateFilters.remove(action.state));
  } else {
    return stubListState.rebuild((b) => b..stateFilters.add(action.state));
  }
}

ListUIState _filterStubs(ListUIState stubListState, FilterStubs action) {
  return stubListState.rebuild((b) => b..filter = action.filter
  ..filterClearedAt = action.filter == null
       ? DateTime.now().millisecondsSinceEpoch
       : stubListState.filterClearedAt);
}

ListUIState _sortStubs(ListUIState stubListState, SortStubs action) {
  return stubListState.rebuild((b) => b
    ..sortAscending = b.sortField != action.field || !b.sortAscending
    ..sortField = action.field);
}

ListUIState _startListMultiselect(
    ListUIState productListState, StartStubMultiselect action) {
  return productListState.rebuild((b) => b..selectedIds = ListBuilder());
}

ListUIState _addToListMultiselect(
    ListUIState productListState, AddToStubMultiselect action) {
  return productListState
      .rebuild((b) => b..selectedIds.add(action.entity.id));
}

ListUIState _removeFromListMultiselect(
    ListUIState productListState, RemoveFromStubMultiselect action) {
  return productListState
      .rebuild((b) => b..selectedIds.remove(action.entity.id));
}

ListUIState _clearListMultiselect(
    ListUIState productListState, ClearStubMultiselect action) {
  return productListState.rebuild((b) => b..selectedIds = null);
}

final stubsReducer = combineReducers<StubState>([
  TypedReducer<StubState, SaveStubSuccess>(_updateStub),
  TypedReducer<StubState, AddStubSuccess>(_addStub),
  TypedReducer<StubState, LoadStubsSuccess>(_setLoadedStubs),
  TypedReducer<StubState, LoadStubSuccess>(_setLoadedStub),
  TypedReducer<StubState, ArchiveStubsRequest>(_archiveStubRequest),
  TypedReducer<StubState, ArchiveStubsSuccess>(_archiveStubSuccess),
  TypedReducer<StubState, ArchiveStubsFailure>(_archiveStubFailure),
  TypedReducer<StubState, DeleteStubsRequest>(_deleteStubRequest),
  TypedReducer<StubState, DeleteStubsSuccess>(_deleteStubSuccess),
  TypedReducer<StubState, DeleteStubsFailure>(_deleteStubFailure),
  TypedReducer<StubState, RestoreStubsRequest>(_restoreStubRequest),
  TypedReducer<StubState, RestoreStubsSuccess>(_restoreStubSuccess),
  TypedReducer<StubState, RestoreStubsFailure>(_restoreStubFailure),
]);

StubState _archiveStubRequest(
    StubState stubState, ArchiveStubsRequest action) {
  final stubs = action.stubIds.map((id) => stubState.map[id]).toList();

  for (int i = 0; i < stubs.length; i++) {
    stubs[i] = stubs[i]
        .rebuild((b) => b..archivedAt = DateTime.now().millisecondsSinceEpoch);
  }
  return stubState.rebuild((b) {
    for (final stub in stubs) {
      b.map[stub.id] = stub;
    }
  });
}

StubState _archiveStubSuccess(
    StubState stubState, ArchiveStubsSuccess action) {
  return stubState.rebuild((b) {
    for (final stub in action.stubs) {
      b.map[stub.id] = stub;
    }
  });
}

StubState _archiveStubFailure(
    StubState stubState, ArchiveStubsFailure action) {
  return stubState.rebuild((b) {
    for (final stub in action.stubs) {
      b.map[stub.id] = stub;
    }
  });
}

StubState _deleteStubRequest(
    StubState stubState, DeleteStubsRequest action) {
  final stubs = action.stubIds.map((id) => stubState.map[id]).toList();

  for (int i = 0; i < stubs.length; i++) {
    stubs[i] = stubs[i].rebuild((b) => b
      ..archivedAt = DateTime.now().millisecondsSinceEpoch
      ..isDeleted = true);
  }
  return stubState.rebuild((b) {
    for (final stub in stubs) {
      b.map[stub.id] = stub;
    }
  });
}

StubState _deleteStubSuccess(
    StubState stubState, DeleteStubsSuccess action) {
  return stubState.rebuild((b) {
    for (final stub in action.stubs) {
      b.map[stub.id] = stub;
    }
  });
}

StubState _deleteStubFailure(
    StubState stubState, DeleteStubsFailure action) {
  return stubState.rebuild((b) {
    for (final stub in action.stubs) {
      b.map[stub.id] = stub;
    }
  });
}

StubState _restoreStubRequest(
    StubState stubState, RestoreStubsRequest action) {
  final stubs = action.stubIds.map((id) => stubState.map[id]).toList();

  for (int i = 0; i < stubs.length; i++) {
    stubs[i] = stubs[i].rebuild((b) => b
      ..archivedAt = null
      ..isDeleted = false);
  }
  return stubState.rebuild((b) {
    for (final stub in stubs) {
      b.map[stub.id] = stub;
    }
  });
}

StubState _restoreStubSuccess(
    StubState stubState, RestoreStubsSuccess action) {
  return stubState.rebuild((b) {
    for (final stub in action.stubs) {
      b.map[stub.id] = stub;
    }
  });
}

StubState _restoreStubFailure(
    StubState stubState, RestoreStubsFailure action) {
  return stubState.rebuild((b) {
    for (final stub in action.stubs) {
      b.map[stub.id] = stub;
    }
  });
}

StubState _addStub(StubState stubState, AddStubSuccess action) {
  return stubState.rebuild((b) => b
    ..map[action.stub.id] = action.stub
    ..list.add(action.stub.id));
}

StubState _updateStub(StubState stubState, SaveStubSuccess action) {
  return stubState.rebuild((b) => b
    ..map[action.stub.id] = action.stub);
}

StubState _setLoadedStub(
    StubState stubState, LoadStubSuccess action) {
  return stubState.rebuild((b) => b
    ..map[action.stub.id] = action.stub);
}

StubState _setLoadedStubs(
        StubState stubState, LoadStubsSuccess action) =>
    stubState.loadStubs(action.stubs);
