//
//  QrCodeViewController.swift
//  Kalker

import UIKit
import CoreData
import EFQRCode

class QrCodeViewController: UIViewController {

    var managedObjectContext: NSManagedObjectContext!
    var loginUser = [User]()
    
    @IBOutlet weak var subView: UIView!
    @IBOutlet weak var qrCode: UIImageView!
    @IBOutlet weak var token: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        subView.layer.cornerRadius = 5
        subView.layer.masksToBounds = true
        
        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        loadLoginUserDataFormCoreData()
        
        if let tryImage = EFQRCode.generate(
            content: self.token.text!
            ) {
            print("Create QRCode image success: \(tryImage)")
            qrCode.image? = UIImage(cgImage: tryImage)
        } else {
            print("Create QRCode image failed!")
        }
    }
    
    func loadLoginUserDataFormCoreData() {
        let fetchRequest: NSFetchRequest<User> = User.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "isLogin == %@", NSNumber(booleanLiteral: true))
        
        do {
            loginUser = try managedObjectContext.fetch(fetchRequest)
            token.text = loginUser.first?.tokenConnection
        } catch {
            print("Błąd podczas ładowania informacji o użytkowniku \(error.localizedDescription)")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func closeButton(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }
}
