//
//  ListPatientViewController.swift
//  Kalker

import UIKit
import CoreData
import Alamofire
import SwiftyJSON
import SDWebImage

class ListPatientViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var managedObjectContext: NSManagedObjectContext!
    var loginUser = [User]()
    var avatar: UIImage!
    var idCaregiver: Int32!
    var json: JSON!
    var rowCount = 0
    var idProfilePatient: Int!
    
    var listPatientId: [Int] = []
    var listPatientName: [String] = []
    var listPatientAvatar: [Bool] = []
    
    @IBOutlet weak var addPatientButton: UIButton!
    @IBOutlet weak var subView: UIView!
    
    @IBOutlet weak var patientTableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setDefaultBackground(viewForBackground: self.view)
        setWhiteBackground(viewForBackground: self.subView)
        
        patientTableView.backgroundColor = UIColor.clear
        
        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 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)")
        }
    }
    
    func loadListCaregiver() {
        self.listPatientId.removeAll()
        self.listPatientName.removeAll()
        self.listPatientAvatar.removeAll()
        
        let parameters = ["idCaregiver": idCaregiver!]
        
        Alamofire.request("https://kalkerapp.pl/api/listPatient.php", method: .post, parameters: parameters)
            .responseJSON { response in
                if let jsonData = response.result.value {
                    self.json = JSON(jsonData)
                    self.rowCount = self.json.count
                    print(self.json)
                    
                    for i in 0..<self.rowCount {
                        self.listPatientId.append(Int(self.json[i]["id"].string!)!)
                        self.listPatientName.append(self.json[i]["name"].string!)
                        
                        if self.json[i]["avatar"].string! == "" {
                            self.listPatientAvatar.append(false)
                        }
                        else {
                            self.listPatientAvatar.append(true)
                        }
                    }
                    
                    DispatchQueue.main.async() {
                        self.patientTableView.reloadData()
                    }
                }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewDidLayoutSubviews() {
        addPatientButton.setWhiteButton()
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rowCount
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = patientTableView.dequeueReusableCell(withIdentifier: "cellPatientList") as? CellPatientList
        
        cell?.name.text = self.listPatientName[indexPath.row]
        
        if self.listPatientAvatar[indexPath.row] == false {
            cell?.avatar.image = UIImage(named: "avatarDefault")
        }
        else {
            cell?.avatar.sd_setImage(with: URL(string: "https://kalkerapp.pl/avatar/p/\(self.listPatientId[indexPath.row]).jpg"), placeholderImage: UIImage(named: "avatarDefault"))
        }
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        patientTableView.deselectRow(at: indexPath, animated: true)
        idProfilePatient = self.listPatientId[indexPath.row]
        performSegue(withIdentifier: "showProfile", sender: indexPath)
    }
    
    @IBAction func clickButton(_ sender: UIButton) {
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 5, options: [], animations: {
            self.addPatientButton.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
        }, completion: { finished in
            UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 5, options: .curveEaseInOut, animations: {
                self.addPatientButton.transform = CGAffineTransform(scaleX: 1, y: 1)
                self.performSegue(withIdentifier: "showAddQR", sender: self)
            }, completion: nil
            )
        }
        )
    }
    
    override func viewWillAppear(_ animated: Bool) {
        setTransparentNavigationBar(navBar: self.navigationController!)
        loadListCaregiver()
        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)
    }
    
    // MARK: - Navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showProfile" {
            let vc = segue.destination as! ProfileViewController
            vc.idPatient = idProfilePatient
            vc.idCaregiver = Int(idCaregiver)
        }
    }
}
