//
//  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"
                NSLog("Transaction Approved")
                NSLog("Product Identifier: \(transaction.payment.productIdentifier)")
                
                // this is where you would validate the receipt...
                // Load the receipt from the app bundle.
                let receiptURL = NSBundle.mainBundle().appStoreReceiptURL
                let receipt = NSData(contentsOfURL: receiptURL!)
                if ((receipt == nil)) {
                    // No local receipt -- handle the error.
                }
                else {
                    // Send the receipt data to your server
                }
                
                // if there is hosted content, download content before finishing the transaction
                
//                SKPaymentQueue.defaultQueue().finishTransaction(transaction)
                SKPaymentQueue.defaultQueue().startDownloads(transaction.downloads)
                
            case SKPaymentTransactionState.Failed:
                NSLog("Transaction Failed");
                lblStatus.text = "Purchase failed";
                SKPaymentQueue.defaultQueue().finishTransaction(transaction)
            default:
                break
            }
        }
    }
    
    func paymentQueue(queue: SKPaymentQueue, updatedDownloads downloads: [SKDownload]) {
        for download in downloads {

            switch download.downloadState {
                
            case SKDownloadState.Active:
                    NSLog("%f", download.progress);
                    NSLog("%f remaining", download.timeRemaining);
                
            case SKDownloadState.Cancelled: break

            case SKDownloadState.Failed:
                    NSLog("Download Failed");
                    lblStatus.text = "Download failed"
                
            case SKDownloadState.Finished:
                    var source = download.contentURL!.path! as NSString
                    
                    // files are in Contents directory
                    source = source.stringByAppendingPathComponent("Contents") as NSString
                    copyFiles(source)
                    
                    SKPaymentQueue.defaultQueue().finishTransaction(download.transaction)
                    NSLog("Download Complete")
                    lblStatus.text = "Download Complete"
                
            case SKDownloadState.Paused:
                    NSLog("SKDownloadStatePaused")
                
            case SKDownloadState.Waiting:
                    NSLog("SKDownloadStateWaiting")
            }
        }

    }

    func copyFiles(source: NSString) {
        
        let fileManager:NSFileManager = NSFileManager.defaultManager()
        let paths:NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let documentsDirectory = paths[0] as! NSString
        
        do {
            let files: NSArray = try fileManager.contentsOfDirectoryAtPath(source as String)
            for file in files {
                let sourcePath = source.stringByAppendingPathComponent(file as! String)
                let targetPath = documentsDirectory.stringByAppendingPathComponent(file as! String)
                try fileManager.copyItemAtPath(sourcePath, toPath: targetPath)
                NSLog("Copied file: %@", file as! String)
            }
        }
        catch let error as NSError {
            NSLog("Error copying file: %@", error.localizedDescription)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

