//
//  ViewController.swift
//  InAppPurchase
//
//  Created by Keith Welch on 1/10/16.
//  Copyright © 2016 Keith Welch. All rights reserved.
//

import UIKit
import StoreKit

class ViewController: UIViewController, SKPaymentTransactionObserver, SKProductsRequestDelegate {

    @IBOutlet weak var btnBuyAccess: UIButton!
    @IBOutlet weak var lblStatus: UILabel!
    @IBOutlet weak var btnPremiumFeature: UIButton!
    
    var product: SKProduct!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        btnBuyAccess.userInteractionEnabled = false
        SKPaymentQueue.defaultQueue().addTransactionObserver(self)
        getProductInfo()
    }

    func getProductInfo() {
        if (SKPaymentQueue.canMakePayments()) {
            let productIdentifiers = Set(["com.mooseworkssoftware.premiumaccess"])
            let request: SKProductsRequest = SKProductsRequest.init(productIdentifiers: productIdentifiers)
            request.delegate = self
            request.start()
        }
        else {
            lblStatus.text = "In App Purchase is not enabled"
        }
    }
    
    func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
        
        var products = response.products
        
        if (products.count != 0)
        {
            product = products[0];
            btnBuyAccess.userInteractionEnabled = true
            lblStatus.text = "Ready for purchase"
        } else {
            lblStatus.text = "Product not found"
        }
        
        let invalidProducts = response.invalidProductIdentifiers
        
        for invalidProduct in invalidProducts
        {
            NSLog("Product not found: %@", invalidProduct);
        }
    }
    
    @IBAction func btnBuyAccessTouched(sender: AnyObject) {
        let payment: SKPayment = SKPayment(product: product)
        SKPaymentQueue.defaultQueue().addPayment(payment)
    }
    
    func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        
        for transaction in transactions {
            
            switch transaction.transactionState {
                
            case SKPaymentTransactionState.Purchased:
                btnPremiumFeature.userInteractionEnabled = true
                lblStatus.text = "Purchase complete"
                SKPaymentQueue.defaultQueue().finishTransaction(transaction)
                NSLog("Transaction Approved")
                NSLog("Product Identifier: \(transaction.payment.productIdentifier)")
                
            case SKPaymentTransactionState.Failed:
                NSLog("Transaction Failed");
                lblStatus.text = "Purchase failed";
                SKPaymentQueue.defaultQueue().finishTransaction(transaction)
            default:
                break
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

