//
//  ProfileViewController.swift
//  Kalker

import UIKit
import CoreData
import Alamofire
import SwiftyJSON
import SDWebImage

class ProfileViewController: UIViewController {

    var managedObjectContext: NSManagedObjectContext!
    var loginUser = [User]()
    var avatarNav: UIImage!
    var idPatient: Int!
    var idCaregiver: Int!
    
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UITextView!
    @IBOutlet weak var avatar: UIImageView!
    @IBOutlet weak var birthLabel: UILabel!
    
    @IBOutlet weak var subView: UIView!
    
    @IBOutlet weak var storyButton: UIButton!
    @IBOutlet weak var deleteButton: UIButton!
    @IBOutlet weak var personalNoteButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setDefaultBackground(viewForBackground: self.view)
        setWhiteBackground(viewForBackground: self.subView)

        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        loadLoginUserDataFromCoreData()
        
        loadProfile()
        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)
            avatarNav = UIImage(data: (loginUser.first?.avatar)! as Data)
            
        } catch {
            print("Błąd podczas ładowania informacji o użytkowniku \(error.localizedDescription)")
        }
    }
    
    func loadProfile() {
        let parameters: Parameters = ["idPatient": idPatient]
        
        Alamofire.request("https://kalkerapp.pl/api/patient.php", method: .post, parameters: parameters)
            .responseJSON { response in
                if let jsonData = response.result.value {
                    let json = JSON(jsonData)
                    
                    self.nameLabel.text = json[0]["name"].string!
                    self.descriptionLabel.text = json[0]["description"].string!
                    self.birthLabel.text = "\(ageFromDate(date: json[0]["birth"].string!)) lat"
                    
                    if json[0]["avatar"].string! == "" {
                        self.avatar.image = UIImage(named: "avatarDefault")
                    }
                    else {
                        self.avatar.sd_setImage(with: URL(string: "https://kalkerapp.pl/avatar/p/\(json[0]["avatar"])"), placeholderImage: UIImage(named: "avatarDefault"))
                    }
                }
        }
    }
    
    @IBAction func showStory(_ sender: UIButton) {
        performSegue(withIdentifier: "showStory", sender: nil)
    }
    
    @IBAction func deleteAccount(_ sender: UIButton) {
        let alert = UIAlertController(title: "Kalker", message: "Czy na pewno chcesz usunąć to konto z listy pacjentów?", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Anuluj", style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in
            switch action.style{
            case .default:
                let parameters: Parameters = ["idPatient": self.idPatient,
                                              "idCaregiver": self.idCaregiver]
                
                Alamofire.request("https://kalkerapp.pl/api/delete.php", method: .post, parameters: parameters)
                    .responseJSON { response in
                        if let jsonData = response.result.value {
                            let json = JSON(jsonData)
                            print(json)
                        }
                }
                
                self.performSegue(withIdentifier: "backToList", sender: nil)
                
            case .cancel:
                print("cancel")
                
            case .destructive:
                print("destructive")
            }
        }))
        self.present(alert, animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewDidLayoutSubviews() {
        avatar.setRoundImage()
        avatar.setBorderImage()
        
        deleteButton.setRoundedButton()
        storyButton.setRoundedButton()
        personalNoteButton.setWhiteButton()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        setTransparentNavigationBar(navBar: self.navigationController!)
        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)
    }
    
    @IBAction func clickButton(_ sender: UIButton) {
        clickAnimation(button: personalNoteButton)
    }
    
    @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 == "showStory" {
            let vc = segue.destination as! PatientStoryViewController
            vc.idPatient = idPatient
        }
        if segue.identifier == "showNote" {
            let vc = segue.destination as! NoteViewController
            vc.idPatient = idPatient
            vc.idCaregiver = idCaregiver
        }
        if segue.identifier == "backToList" {
            let vc = segue.destination as! CaregiverCallsViewController
            vc.idLast = 0
        }
    }
}
