<commit_before>//
//  MasterViewController.swift
//  RxAlamofire
//
//  Created by <NAME>. on 23/08/15.
//  Copyright © 2015 <EMAIL>. All rights reserved.
//

import UIKit
import Alamofire
import RxSwift
import RxAlamofire

class MasterViewController: UIViewController, UITextFieldDelegate {
    
    let sourceStringURL = "http://api.fixer.io/latest?base=EUR&symbols=USD"
    let disposeBag = DisposeBag()
    
    @IBOutlet weak var fromTextField: UITextField!
    @IBOutlet weak var toTextField: UITextField!
    @IBOutlet weak var convertBtn: UIButton!
    @IBOutlet weak var dummyDataBtn: UIButton!
    @IBOutlet weak var dummyDataTextView: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - UI Actions
    
    @IBAction func convertPressed(_ sender: UIButton) {
        fromTextField.resignFirstResponder()
        
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.currencyCode = "USD"
        if let fromValue = NumberFormatter().number(from: self.fromTextField.text ?? "")?.floatValue {
            RxAlamofire.requestJSON(.get, sourceStringURL)
                .debug()
                .subscribe(onNext: { [weak self] (r, json) in
                    if let dict = json as? [String: AnyObject] {
                        let valDict = dict["rates"] as! Dictionary<String, AnyObject>
                        if let conversionRate = valDict["USD"] as? Float {
                            self?.toTextField.text = formatter
                                .string(from: NSNumber(value: conversionRate * fromValue))
                        }
                    }
                    }, onError: { [weak self] (error) in
                        self?.displayError(error as NSError)
                })
                .disposed(by: disposeBag)

        } else {
            self.toTextField.text = "Invalid Input!"
        }
    }


func exampleUsages() {
    
    let stringURL = ""
    // MARK: NSURLSession simple and fast
    let session = URLSession.shared
    _ = session.rx
        .json(.get, stringURL)
        .observeOn(MainScheduler.instance)
        .subscribe { print($0) }
    
    _ = session
        .rx.json(.get, stringURL)
        .observeOn(MainScheduler.instance)
        .subscribe { print($0) }
    
    _ = session
        .rx.data(.get, stringURL)
        .observeOn(MainScheduler.instance)
        .subscribe { print($0) }
    
    // MARK: With Alamofire engine
    
    _ = json(.get, stringURL)
        .observeOn(MainScheduler.instance)
        .subscribe { print($0) }
    
    <commit_msg>Fix api error in exmaple<commit_after>//
//  MasterViewController.swift
//  RxAlamofire
//
//  Created by <NAME>. on 23/08/15.
//  Copyright © 2015 Bonto.ch. All rights reserved.
//

import UIKit
import Alamofire
import RxSwift
import RxAlamofire

enum APIError: Error {
    case invalidInput
    case badResposne
    
    func toNSError() -> NSError {
        let domain = "com.github.rxswiftcommunity.rxalamofire"
        switch self {
        case .invalidInput:
            return NSError(domain: domain, code: -1, userInfo: [NSLocalizedDescriptionKey: "Input should be a valid number"])
        case .badResposne:
            return NSError(domain: domain, code: -2, userInfo: [NSLocalizedDescriptionKey: "Bad response"])
        }
    }
}

class MasterViewController: UIViewController, UITextFieldDelegate {
    
    let disposeBag = DisposeBag()
    let exchangeRateEndpoint = "https://api.exchangeratesapi.io/latest?base=EUR&symbols=USD"
    
    @IBOutlet weak var fromTextField: UITextField!
    @IBOutlet weak var toTextField: UITextField!
    @IBOutlet weak var convertBtn: UIButton!
    @IBOutlet weak var dummyDataBtn: UIButton!
    @IBOutlet weak var dummyDataTextView: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    // MARK: - UI Actions
    
    @IBAction func convertPressed(_ sender: UIButton) {
        fromTextField.resignFirstResponder()
        
        guard let fromText = self.fromTextField.text, let fromValue = Double(fromText) else {
            self.displayError(APIError.invalidInput.toNSError())
            return
        }
        
        RxAlamofire.requestJSON(.get, exchangeRateEndpoint)
            .debug()
            .flatMap { (_, json) -> Observable<Double> in
                guard
                    let body = json as? [String: Any],
                    let rates = body["rates"] as? [String: Any],
                    let rate = rates["USD"] as? Double
                else {
                    return .error(APIError.badResposne.toNSError())
                }
                return .just(rate)
            }
            .subscribe(onNext: { [weak self] (rate) in
                self?.toTextField.text = "\(rate * fromValue)"
            }, onError: { [weak self] e in
                self?.displayError(e as NSError)
            })
            .disposed(by: self.disposeBag)
    }


func exampleUsages() {
    
    let stringURL = ""
    // MARK: NSURLSession simple and fast
    let session = URLSession.shared
    _ = session.rx
        .json(.get, stringURL)
        .observeOn(MainScheduler.instance)
        .subscribe { print($0) }
    
    _ = session
        .rx.json(.get, stringURL)
        .observeOn(MainScheduler.instance)
        .subscribe { print($0) }
    
    _ = session
        .rx.data(.get, stringURL)
        .observeOn(MainScheduler.instance)
        .subscribe { print($0) }
    
    // MARK: With Alamofire engine
    
    _ = json(.get, stringURL)
        .observeOn(MainScheduler.instance)
        .subscribe { print($0) }
    
    
{'fraction_non_alphanumeric': 0.10060463553913336, 'fraction_numerical': 0.0050386294927779645, 'mean_word_length': 1.9363905325443787, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 10, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5999109', 'n_tokens_mistral': 1814, 'n_tokens_neox': 1700, 'n_words': 402}