import 'package:aman_kassa_flutter/core/locator.dart';
import 'package:aman_kassa_flutter/core/logger.dart';
import 'package:aman_kassa_flutter/core/models/forte/forte_close_day_dao.dart'
    as Cd;
import 'package:aman_kassa_flutter/core/models/forte/forte_response_dao.dart';
import 'package:aman_kassa_flutter/core/services/DataService.dart';
import 'package:aman_kassa_flutter/core/services/dialog_service.dart';
import 'package:aman_kassa_flutter/core/services/navigator_service.dart';
import 'package:aman_kassa_flutter/redux/store.dart';
import 'package:logger/logger.dart';
import '../../core/models/aman_dao.dart';
import '../../core/models/card_data.dart';
import '../../core/models/forte/forte_post_session.dart';
import '../../core/services/ForteService.dart';
import '../../redux/state/bank_state.dart';

ForteService _bankService = locator<ForteService>();
DialogService _dialogService = locator<DialogService>();
final DataService _dataService = locator<DataService>();
final NavigatorService _navigatorService = locator<NavigatorService>();
Logger log = getLogger('PaymentNfcView');

Future<AmanDao<CardData>> paymentFortePos(double total) async {
  //Авторизация
  String token = Redux.store!.state.userState!.user!.token!;
  BankState bankState = Redux.store!.state.bankState!;
  //права доступа
  FortePosSession? session = await _bankService.renewToken(
      token: token, login: bankState.login!, password: bankState.password!);
  if (session == null || session.token == null) {
    return sessionDeclineDao(session);
  }

  //Инициализация
  ForteResponse response =
      await _bankService.pay(token: session.token!, amount: total);
  if (response.result?.code == 0) {
    CardData cardData = new CardData(
        authorizationCode:
            response.transaction?.instrumentSpecificData?.authorizationCode,
        cardholderName:
            response.transaction?.instrumentSpecificData?.cardholderName,
        cardNumber: response.transaction?.instrumentSpecificData?.maskedPan,
        operationDay: response.transaction?.operationDay,
        transactionNumber: response.transaction?.transactionNumber,
        terminalId: response.transaction?.terminalId,
        transactionType: 'payment');
    return AmanDao<CardData>(
        msg: response.result?.description, success: true, data: cardData);
  }
  return AmanDao<CardData>(
      msg: response.result?.errorData != null
          ? response.result!.errorData!.description
          : response.result!.description,
      success: false);
}

AmanDao<CardData> sessionDeclineDao(FortePosSession? session) {
  String msg = 'Отказано в доступе к API банка';
  if(session!=null && session.result?.Response?.Description != null) {
    msg = '${session.result?.Response?.Description} (${session.result?.Response?.Code}) ';
  }
  return AmanDao<CardData>(success: false, msg: msg);
}

Future<AmanDao<CardData>> refundFortePos(
    CardData refundData, double total) async {
  //Авторизация
  String token = Redux.store!.state.userState!.user!.token!;
  BankState bankState = Redux.store!.state.bankState!;
  //права доступа
  FortePosSession? session = await _bankService.renewToken(
      token: token, login: bankState.login!, password: bankState.password!);
  if (session == null || session.token == null) {
    return sessionDeclineDao(session);
  }
  ForteResponse response = await _bankService.refund(
      token: session.token!,
      amount: total,
      operDay: refundData.operationDay!,
      terminalId: refundData.terminalId!,
      transNum: refundData.transactionNumber!);
  if (response.result?.code == 0) {
    CardData cardData = new CardData(
        authorizationCode:
            response.transaction?.instrumentSpecificData?.authorizationCode,
        cardholderName:
            response.transaction?.instrumentSpecificData?.cardholderName,
        cardNumber: response.transaction?.instrumentSpecificData?.maskedPan,
        operationDay: response.transaction?.operationDay,
        transactionNumber: response.transaction?.transactionNumber,
        terminalId: response.transaction?.terminalId,
        transactionType: 'refund');
    return AmanDao<CardData>(
        msg: response.result?.description, success: true, data: cardData);
  }
  return AmanDao<CardData>(
      msg: response.result?.errorData != null
          ? response.result!.errorData!.description
          : response.result!.description,
      success: false);
}

Future<AmanDao<CardData>> reversalFortePos(
    CardData refundData, double total) async {
  //Авторизация
  String token = Redux.store!.state.userState!.user!.token!;
  BankState bankState = Redux.store!.state.bankState!;
  //права доступа
  FortePosSession? session = await _bankService.renewToken(
      token: token, login: bankState.login ?? '', password: bankState.password ?? '');
  if (session == null || session.token == null) {
    return sessionDeclineDao(session);
  }
  log.i(refundData.toJson());
  ForteResponse response = await _bankService.reversal(
      token: session.token!,
      operDay: refundData.operationDay!,
      terminalId: refundData.terminalId!,
      transNum: refundData.transactionNumber!);
  if (response.result?.code == 0) {
    CardData cardData = new CardData(
        authorizationCode:
            response.transaction?.instrumentSpecificData?.authorizationCode,
        cardholderName:
            response.transaction?.instrumentSpecificData?.cardholderName,
        cardNumber: response.transaction?.instrumentSpecificData?.maskedPan,
        operationDay: response.transaction?.operationDay,
        transactionNumber: response.transaction?.transactionNumber,
        terminalId: response.transaction?.terminalId,
        transactionType: 'reversal');
    return AmanDao<CardData>(
        msg: response.result?.description, success: true, data: cardData);
  }
  return AmanDao<CardData>(
      msg: response.result?.errorData != null
          ? response.result!.errorData!.description
          : response.result!.description,
      success: false);
}

Future<Cd.ForteCloseDayDao?> closeDayFortePos() async {
  //Авторизация
  String token = Redux.store!.state.userState!.user!.token!;
  BankState bankState = Redux.store!.state.bankState!;
  //права доступа
  FortePosSession? session = await _bankService.renewToken(
      token: token, login: bankState.login ?? '', password: bankState.password ?? '');
  if (session== null || session.token == null) {
    return new Cd.ForteCloseDayDao(
        result: Cd.ResultBean(
            description: 'Отказано в доступе к API банка', code: -1));
  }
  //Инициализация
  Cd.ForteCloseDayDao? response =
      await _bankService.closeDay(token: session.token!);
  return response;
}
