//
//  ChargebackViewController.swift
//  Chargebacker
//
//  Created by Lucas Pereira on 24/06/17.
//  Copyright (c) 2017 Lucas Pereira. 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 ChargebackDisplayLogic: class
{
    func displayData(viewModel: Chargeback.Data.ViewModel)
    func cardStateUpdated(blocked: Bool)
    func contestSucceeded()
    func contestFailed(errorMessage: String?)
}

fileprivate let strings = R.string.chargeback.self

class ChargebackViewController: UIViewController, ChargebackDisplayLogic
{
    var interactor: ChargebackBusinessLogic?
    
    // MARK: IBOutlets
    
    @IBOutlet weak var lblTitle: UILabel!
    @IBOutlet weak var btnBlockCard: UIButton!
    @IBOutlet weak var btnContest: UIButton!
    @IBOutlet weak var lblBlockCard: UILabel!
    @IBOutlet weak var lblMerchantRecognized: UILabel!
    @IBOutlet weak var lblCardInPossession: UILabel!
    @IBOutlet weak var switchMerchantRecognized: UISwitch!
    @IBOutlet weak var switchCardInPossession: UISwitch!
    @IBOutlet weak var txtCommentView: UITextView!
    
    // MARK: Properties
    
    var commentPlaceholder = NSAttributedString()
    lazy var tapToDismissKeyboard: UITapGestureRecognizer = { [weak self] in
        guard let welf = self else {  return UITapGestureRecognizer() }
        return UITapGestureRecognizer(target: welf, action: #selector(ChargebackViewController.dismissKeyboard(tapGesture:)))
        }()
    
    // MARK: Object lifecycle
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }
    
    // MARK: Setup
    
    private func setup() {
        let viewController = self
        let interactor = ChargebackInteractor()
        let presenter = ChargebackPresenter()
        viewController.interactor = interactor
        interactor.presenter = presenter
        presenter.viewController = viewController
    }
    
    // MARK: Private API
    
    @objc fileprivate func dismissKeyboard(tapGesture: UITapGestureRecognizer) {
        view.endEditing(true)
    }
    
    // MARK: IBActions
    
    @IBAction func toggledReasonSwitch(_ sender: UISwitch) {
        switch sender {
        case switchMerchantRecognized:
            lblMerchantRecognized.textColor = sender.isOn ? ThemeHandler.greenColor() : ThemeHandler.blackColor()
        case switchCardInPossession:
            lblCardInPossession.textColor = sender.isOn ? ThemeHandler.greenColor() : ThemeHandler.blackColor()
        default: return
        }
    }
    
    @IBAction func tappedLockButton(_ sender: UIButton) {
        interactor?.setCard(blocked: !btnBlockCard.isSelected, showSpinner: true)
    }
    
    @IBAction func tappedContest(_ sender: UIButton) {
        var request = Chargeback.Data.Request(comment: txtCommentView.text ?? "")
        request.addReason(id: .merchant_recognized, response: switchMerchantRecognized.isOn)
        request.addReason(id: .card_in_possession, response: switchCardInPossession.isOn)
        interactor?.tappedContest(request: request)
    }
    
    @IBAction func tappedCancel(_ sender: UIButton) {
        navigationController?.popViewController(animated: true)
    }
    
    // MARK: Display Logic
    
    func displayData(viewModel: Chargeback.Data.ViewModel) {
        lblTitle.text = viewModel.title.uppercased()
        txtCommentView.attributedText = viewModel.hint.attributedStringFromHTML(fontSize: 17)
        txtCommentView.textColor = ThemeHandler.hintColor()
        commentPlaceholder = txtCommentView.attributedText
        lblBlockCard.text = viewModel.autoblock ? strings.cardBlockedMessage() : strings.cardUnblockedMessage()
        btnBlockCard.isSelected = viewModel.autoblock
        if viewModel.autoblock {
            interactor?.setCard(blocked: true, showSpinner: false)
        }
        lblMerchantRecognized.text = viewModel.merchantRecognizedReason.title
        lblCardInPossession.text = viewModel.cardInPossessionReason.title
    }
    
    func cardStateUpdated(blocked: Bool) {
        btnBlockCard.isSelected = blocked
        lblBlockCard.text = blocked ? strings.cardBlockedMessage() : strings.cardUnblockedMessage()
    }
    
    func contestSucceeded() {
        let modalAlert = ModalAlertViewController { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
        present(modalAlert, animated: true, completion: nil)
    }
    
    func contestFailed(errorMessage: String?) {
        GeneralAlerter.displayErrorAlert(message: errorMessage)
    }
}

extension ChargebackViewController: UITextViewDelegate {
    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.textColor != ThemeHandler.blackColor() {
            textView.attributedText = nil
            textView.textColor = ThemeHandler.blackColor()
        }
        view.addGestureRecognizer(tapToDismissKeyboard)
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
            textView.attributedText = commentPlaceholder
            textView.textColor = ThemeHandler.hintColor()
        }
        view.removeGestureRecognizer(tapToDismissKeyboard)
    }
    
    func textViewDidChange(_ textView: UITextView) {
        btnContest.isEnabled = !textView.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
    }
}
