
import 'package:aman_kassa_flutter/core/models/halyk/halyk_post_session.dart';
import 'package:aman_kassa_flutter/core/models/forte/forte_post_session.dart';
import 'package:aman_kassa_flutter/redux/state/bank_state.dart';
import 'package:meta/meta.dart';
import 'package:redux/redux.dart';
import 'package:redux_thunk/redux_thunk.dart';

import '../store.dart';

@immutable
class SetBankStateAction {
  final BankState bankState;
  SetBankStateAction(this.bankState);
}

ThunkAction<AppState> saveData(String login, String password, {String? sessionType}) {
  return (Store<AppState> store) async {
    final currentState = store.state.bankState;

    dynamic session;
    if (sessionType == 'Halyk') {
      session = HalykPosSession(
        login: login,
        token: currentState?.session != null &&
            currentState?.session is HalykPosSession
            ? (currentState?.session as HalykPosSession).token
            : null,
        serverTime: currentState?.session != null &&
            currentState?.session is HalykPosSession
            ? (currentState?.session as HalykPosSession).serverTime
            : null,
        tokenTimeout: currentState?.session != null &&
            currentState?.session is HalykPosSession
            ? (currentState?.session as HalykPosSession).tokenTimeout
            : null,
        result: currentState?.session != null &&
            currentState?.session is HalykPosSession
            ? (currentState?.session as HalykPosSession).result
            : null,
      );
    } else if (sessionType == 'Forte') {
      session = FortePosSession(
        login: login,
        token: currentState?.session != null &&
            currentState?.session is FortePosSession
            ? (currentState?.session as FortePosSession).token
            : null,
        serverTime: currentState?.session != null &&
            currentState?.session is FortePosSession
            ? (currentState?.session as FortePosSession).serverTime
            : null,
        tokenTimeout: currentState?.session != null &&
            currentState?.session is FortePosSession
            ? (currentState?.session as FortePosSession).tokenTimeout
            : null,
        result: currentState?.session != null &&
            currentState?.session is FortePosSession
            ? (currentState?.session as FortePosSession).result
            : null,
      );
    }
    store.dispatch(SetBankStateAction(BankState(
      login: login,
      password: password,
      session: session,
      sessionType: sessionType,
    )));
  };
}

ThunkAction<AppState> setHalykSession(HalykPosSession session) {
  return (Store<AppState> store) async {
    store.dispatch(SetBankStateAction(BankState(session: session)));
  };
}
