//
//  Test2ViewControllerSwift.swift
//  MCPlus
//
//  Created by seo ha on 15/02/2019.
//  Copyright © 2019 KangSH. All rights reserved.
//

import Foundation
import UIKit
import CoreNFC

@available(iOS 11.0, *)
class Test2ViewController: UIViewController {
    
    @IBOutlet weak var scanButton:UIButton!{
        didSet{
            scanButton.addTapGestureRecognizer(action: self.scanAction)
        }
    }
    
    var reuseIdentifier:String?
    var detectedMessages:[NFCNDEFMessage]?
    var session:NFCNDEFReaderSession?
    var callBack:((String)->Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        print("start scan")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

@available(iOS 11.0, *)
extension Test2ViewController{
    
    func scanAction(){
        print("start scan")
        self.session = NFCNDEFReaderSession(delegate: self, queue: DispatchQueue(label: "DISPATCH_QUEUE_CONCURRENT"), invalidateAfterFirstRead: false)
        session?.alertMessage = "Hold your iPhone near the item to learn more about it."
        session?.begin()
    }
    
    func stopScan(){
        session?.invalidate()
    }
}

@available(iOS 11.0, *)
extension Test2ViewController:NFCNDEFReaderSessionDelegate{
    func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
        guard let tag = messages.first?.description else {
            return
        }
        print("tag: \(tag)")
        self.callBack?(tag)
    }
    
    func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
        
    }
    
}
