//
//  TransactionPresenter.swift
//  ExamineSpending
//
//  Copyright (c) 2018 Aleksi Sitomaniemi. All rights reserved.
//
//  This file was generated by the Clean Swift Xcode Templates so
//  you can apply clean architecture to your iOS and Mac projects,
//  see http://clean-swift.com
//

import UIKit

protocol TransactionPresentationLogic {
  func presentDetails(response: TransactionDetails.Fetch.Response)
}

class TransactionPresenter: TransactionPresentationLogic {
  weak var viewController: TransactionDisplayLogic?

  // MARK: Do something
  func presentDetails(response: TransactionDetails.Fetch.Response) {
    log.verbose("")
    let fmt = ISO8601DateFormatter.init()
    fmt.formatOptions = [.withFullDate]

    // Construct data rows. This can be built rather variable depending on transaction types, specific banks etc.
    var dataRows = [RowData(title: "From", value: response.txn.type == .debit ? "Me" : response.txn.debtorName),
                   RowData(title: "To", value: response.txn.type == .credit ? "Me" : response.txn.creditorName),
                   RowData(title: "Date", value: getShortDate(fmt.date(from: response.txn.bookingDate) ?? Date())),
                   RowData(title: "Description", value: response.txn.description)]

    //Filter out rows with no value (e.g. ATM withdrawals have no creditorName)
    dataRows = dataRows.filter({ row in
      return row.value != nil
    })

    let amountString = "\(response.txn.amount) \(response.txn.currency)"
    let viewModel = TransactionDetails.Fetch.ViewModel(amount: amountString, type: response.txn.type, valuePairs: dataRows)
    viewController?.displayTransaction(viewModel: viewModel)
  }

  func getShortDate(_ date: Date) -> String {
    return DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .none)
  }
}
