//
//  ListCaregiverViewController.swift
//  Kalker

import UIKit
import CoreData
import Alamofire
import SwiftyJSON
import SDWebImage

class ListCaregiverViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let defaults: UserDefaults = UserDefaults.standard
    var managedObjectContext: NSManagedObjectContext!
    var loginUser = [User]()
    var avatar: UIImage!
    var idPatient: Int32!
    var idActiveCaregiver: Int32!
    var json: JSON!
    var rowCount = 0
    
    var listCaregiverId: [Int] = []
    var listCaregiverName: [String] = []
    var listCaregiverPhone: [String] = []
    var listCaregiverAvatar: [String] = []
    
    @IBOutlet weak var caregiverTableView: UITableView!
    @IBOutlet weak var subView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setDefaultBackground(viewForBackground: self.view)
        setWhiteBackground(viewForBackground: self.subView)
        
        caregiverTableView.backgroundColor = UIColor.clear
        
        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        loadLoginUserDataFromCoreData()
        loadListCaregiver()
        
        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)
            idPatient = loginUser.first?.id
            idActiveCaregiver = loginUser.first?.activeCaregiver
            avatar = UIImage(data: (loginUser.first?.avatar)! as Data)
            
        } catch {
            print("Błąd podczas ładowania informacji o użytkowniku \(error.localizedDescription)")
        }
    }
    
    func loadListCaregiver() {
        self.listCaregiverId.removeAll()
        self.listCaregiverName.removeAll()
        self.listCaregiverPhone.removeAll()
        self.listCaregiverAvatar.removeAll()
        
        let parameters = ["parameter": 1,
                          "idPatient": idPatient!]
        
        Alamofire.request("https://kalkerapp.pl/api/listCaregiver.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.listCaregiverId.append(Int(self.json[i]["id"].string!)!)
                        self.listCaregiverName.append(self.json[i]["name"].string!)
                        self.listCaregiverPhone.append(self.json[i]["phone"].string!)
                        self.listCaregiverAvatar.append(self.json[i]["avatar"].string!)
                    }
                    
                    DispatchQueue.main.async() {
                        self.caregiverTableView.reloadData()
                    }
                }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    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 = caregiverTableView.dequeueReusableCell(withIdentifier: "cellActiveCaregiver") as? CellCaregiverList
        
        // Ustawienie checkmarka dla aktywnego
        if Int(idActiveCaregiver) == self.listCaregiverId[indexPath.row] {
            cell?.accessoryType = .checkmark
        }
        
        cell?.name.text = self.listCaregiverName[indexPath.row]
        
        if self.listCaregiverAvatar[indexPath.row] == "" {
            cell?.avatar.image = UIImage(named: "avatarDefault")
        }
        else {
            cell?.avatar.sd_setImage(with: URL(string: "https://kalkerapp.pl/avatar/c/\(self.listCaregiverAvatar[indexPath.row])"), placeholderImage: UIImage(named: "avatarDefault"))
        }
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        if let cell = caregiverTableView.cellForRow(at: indexPath) {
            cell.accessoryType = .none
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //caregiverTableView.deselectRow(at: indexPath, animated: true)
        if let cell = caregiverTableView.cellForRow(at: indexPath) {
            cell.accessoryType = .checkmark
            
            // Zapis do SQL
            let parameters = ["parameter": 2,
                              "idPatient": idPatient!,
                              "activeCaregiver": self.listCaregiverId[indexPath.row]] as [String : Any]
            
            Alamofire.request("https://kalkerapp.pl/api/listCaregiver.php", method: .post, parameters: parameters)
                .responseJSON { response in
                    //if let jsonData = response.result.value {
                        //let savejson = JSON(jsonData)
                    //}
            }
            
            // Zapis do CoreData
            let fetchRequest: NSFetchRequest<User> = User.fetchRequest()
            
            do {
                let array_users = try managedObjectContext.fetch(fetchRequest)
                let user = array_users[0]
                
                user.setValue(Int32(self.listCaregiverId[indexPath.row]), forKey: "activeCaregiver")

                do {
                    try self.managedObjectContext.save()
                } catch {
                    print("Błąd podczas zapisu aktywnego opiekuna \(error.localizedDescription)")
                }
            } catch {
                print("Błąd podczas wysłania zapytania zapisu \(error.localizedDescription)")
            }
            //
            
            _ = navigationController?.popViewController(animated: true)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        setTransparentNavigationBar(navBar: self.navigationController!)
        NotificationCenter.default.addObserver(self, selector: #selector(observeNotificationPatient(notification:)), name: Notification.Name("SendPatientNotif"), object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(self, name: Notification.Name("SendPatientNotif"), object: nil)
    }
    
    @objc func observeNotificationPatient(notification: Notification) {
        // Open PatientView
        let alert = setNotifForPatient(title: defaults.string(forKey: "patientNotifTitle")!, message: defaults.string(forKey: "patientNotifBody")!, navcontroller: navigationController!)
        self.present(alert, animated: true, completion: nil)
    }
}
