//
//  OnlinePaymentFormViewController.swift
//  kt
//
//  Created by Assylkhan Rakhatov on 20.05.16.
//  Copyright © 2016 Alexandr Zalutskiy. All rights reserved.
//

import Foundation
import UIKit

class OnlinePaymentFormViewController: UIViewController, UIWebViewDelegate {
    @IBOutlet weak var webView: UIWebView!
    var data: NSData?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        PKNotification.loading(true)
        webView.delegate = self
        var json = JSON(data: data!)
        guard let postData = json["post_data"].dictionaryObject, let formUrl = json["url"].string else {
            PKNotification.loading(false);
            AlertViewUtil.showErrorAlert(LS("error"), vc: self);
            return
        }
        var mutableRequest = NSMutableURLRequest(URL: NSURL(string: formUrl)!)
        mutableRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
        mutableRequest.HTTPMethod = "POST"
        let requestWithParam = ParameterEncoding.JSON.encode(mutableRequest, parameters: postData).0
        mutableRequest = requestWithParam.mutableCopy() as! NSMutableURLRequest
        webView.loadRequest(mutableRequest)
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        webView.scrollView.bounces = false
    }
    
}

// UIWebViewDelegate
extension OnlinePaymentFormViewController {
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
        AlertViewUtil.showErrorAlert(LS("error"), message: error.localizedDescription ?? error.localizedDescription)
        print("didFailLoadWithError")
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        print("webViewDidFinishLoad")
        webView.scalesPageToFit = true
        PKNotification.loading(false)
    }
}
