//
//  AddPatientViewController.swift
//  Kalker

import UIKit
import CoreData
import AVFoundation
import Alamofire
import SwiftyJSON

class AddPatientViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {

    var managedObjectContext: NSManagedObjectContext!
    var loginUser = [User]()
    var avatar: UIImage!
    var idCaregiver: Int32!
    
    var video = AVCaptureVideoPreviewLayer()
    
    @IBOutlet weak var tokenTextField: UITextField!
    @IBOutlet weak var addButton: UIButton!
    @IBOutlet weak var viewQR: UIView!
    @IBOutlet weak var frameQR: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.hideKeyboardWhenTappedAround()
        
        let session = AVCaptureSession()
        let captureDevice = AVCaptureDevice.default(for: AVMediaType.video)
        
        do {
            let input = try AVCaptureDeviceInput(device: captureDevice!)
            session.addInput(input)
        } catch {
            print("error init camera")
        }
        
        let output = AVCaptureMetadataOutput()
        session.addOutput(output)
        
        output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        output.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
        
        viewQR.frame = self.view.layer.bounds
        video = AVCaptureVideoPreviewLayer(session: session)
        video.frame = viewQR.layer.bounds
        viewQR.layer.addSublayer(video)
        viewQR.bringSubview(toFront: frameQR)
        
        session.startRunning()

        setDefaultBackground(viewForBackground: self.view)
        
        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        loadLoginUserDataFromCoreData()
        navBarButtons()
    }
    
    func navBarButtons() {
        // Przycisk profilu/ustawień
        let button = profileButtonInNavigationBar(img: UIImage.init(named: "settingsIcon")!)
        button.addTarget(self, action: #selector(openProfileSetting), for: .touchUpInside)
        let barButton = UIBarButtonItem.init(customView: button)
        
        navigationItem.setRightBarButtonItems([barButton], animated: false)
    }
    
    @objc func openProfileSetting(sender: UIBarButtonItem) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "settingsView") as! SettingsViewController
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        if metadataObjects.count != 0 {
            if let object = metadataObjects[0] as? AVMetadataMachineReadableCodeObject {
                if object.type == AVMetadataObject.ObjectType.qr {
                    tokenTextField.text = object.stringValue
                    self.add()
                }
            }
        }
    }
    
    func loadLoginUserDataFromCoreData() {
        let fetchRequest: NSFetchRequest<User> = User.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "isLogin == %@", NSNumber(booleanLiteral: true))
        
        do {
            loginUser = try managedObjectContext.fetch(fetchRequest)
            idCaregiver = loginUser.first?.id
            avatar = UIImage(data: (loginUser.first?.avatar)! as Data)
            
        } catch {
            print("Błąd podczas ładowania informacji o użytkowniku \(error.localizedDescription)")
        }
    }
    
    @IBAction func addPatient(_ sender: UIButton) {
        self.add()
    }
    
    func add() {
        if tokenTextField.text != "" {
            let parameters: Parameters = ["idCaregiver": idCaregiver,
                                          "tokenConnection": tokenTextField.text!
            ]
            
            Alamofire.request("https://kalkerapp.pl/api/connect.php", method: .post, parameters: parameters)
                .responseJSON { response in
                    if let jsonData = response.result.value {
                        let json = JSON(jsonData)
                        print(json)
                        if json[0]["id"] == 0 {
                            let alert = setAlert(title: "Kalker", message: "Brak użytkownika w bazie")
                            self.present(alert, animated: true, completion: nil)
                        }
                        else if json[0]["id"] == 1 {
                            let alert = setAlert(title: "Kalker", message: "Jesteś już połączony z \(json[0]["name"])")
                            self.present(alert, animated: true, completion: nil)
                        }
                        else if json[0]["id"] == 2 {
                            let alert = setAlert(title: "Kalker", message: "Użytkownik \(json[0]["name"]) został dodany")
                            self.present(alert, animated: true, completion: nil)
                        }
                    }
            }
        }
        else {
            let alert = setAlert(title: "Kalker", message: "Wypełnij wymagane pole")
            self.present(alert, animated: true, completion: nil)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewDidLayoutSubviews() {
        addButton.setWhiteButton()
        tokenTextField.setDefaultTextField()
    }
    
    @IBAction func clickButton(_ sender: UIButton) {
        clickAnimation(button: addButton)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        NotificationCenter.default.addObserver(self, selector: #selector(observeNotification(notification:)), name: Notification.Name("SendCaregiverNotif"), object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(self, name: Notification.Name("SendCaregiverNotif"), object: nil)
    }
    
    @objc func observeNotification(notification: Notification) {
        // Open CaregiverView
        let alert = setNotifForCaregiver(title: "Kalker", message: "Odebrałeś nową potrzebę", navcontroller: navigationController!)
        self.present(alert, animated: true, completion: nil)
    }
}
