//
//  PatientCallsViewController.swift
//  Kalker

import UIKit
import CoreData
import Alamofire
import SwiftyJSON

class PatientCallsViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    let defaults: UserDefaults = UserDefaults.standard
    var managedObjectContext: NSManagedObjectContext!
    var loginUser = [User]()
    var avatar: UIImage!
    var idPatient: Int32!
    var idActiveCaregiver: Int32!
    
    var activeCaregiverJSON: JSON!
    
    @IBOutlet weak var subView: UIView!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var caregiverButton: UIButton!
    @IBOutlet weak var caregiverPhoneButton: UIButton!
    @IBOutlet weak var alarmPhoneButton: UIButton!
    
    let callsTitle = Call.getCallTitle()
    let callsImage = Call.getCallImage()
    
    var numberOfItemsPerRow: CGFloat!
    
    var sendCallId: Int!
    var sendCaregiverId: Int!
    var sendPatientId: Int!
    
    struct Storyboard {
        static let padding: CGFloat = 10.0
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        switch UIDevice.current.userInterfaceIdiom {
            case .phone:
                numberOfItemsPerRow = 2.0
            case .pad:
                numberOfItemsPerRow = 3.0
            default:
                numberOfItemsPerRow = 2.0
        }

        setDefaultBackground(viewForBackground: self.view)
        setWhiteBackground(viewForBackground: self.subView)
        
        collectionView.backgroundColor = UIColor.clear
        let collectionViewWidth = self.view.frame.width
        let itemWidth = ((collectionViewWidth - Storyboard.padding) / numberOfItemsPerRow) - 10.0
        
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth + 10.0)

        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    }
    
    func navBarButtons() {
        navigationItem.hidesBackButton = true
        
        // 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
        //vc.navigationItem.backBarButtonItem?.title = "Wróć"
        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 loadDataActiveCaregiver() {
        let parameters = ["parameter": 3,
                          "idPatient": idPatient!,
                          "activeCaregiver": idActiveCaregiver!]
        
        Alamofire.request("https://kalkerapp.pl/api/listCaregiver.php", method: .post, parameters: parameters)
            .responseJSON { response in
                if let jsonData = response.result.value {
                    self.activeCaregiverJSON = JSON(jsonData)
                    
                    if (self.activeCaregiverJSON[0]["name"].null != nil) {
                        self.caregiverButton.setTitle("Wybierz opiekuna", for: .normal)
                        self.caregiverPhoneButton.isHidden = true
                    } else {
                        self.caregiverButton.setTitle("Opiekun: \(self.activeCaregiverJSON[0]["name"])", for: .normal)
                        self.caregiverPhoneButton.isHidden = false
                    }
                }
        }
    }
    
    @IBAction func clickButton(_ sender: UIButton) {
        clickAnimation(button: caregiverButton)
    }
    
    @IBAction func caregiverPhone(_ sender: UIButton) {
        clickAnimation(button: caregiverPhoneButton)
        let alert = setPhoneAlert(title: "Kalker", message: "Czy na pewno chcesz zadzwonić do \(self.activeCaregiverJSON[0]["name"])?", phone: "\(self.activeCaregiverJSON[0]["phone"])")
        self.present(alert, animated: true, completion: nil)
    }

    @IBAction func alarmPhone(_ sender: UIButton) {
        clickAnimation(button: alarmPhoneButton)
        let alert = setPhoneAlert(title: "Kalker", message: "Czy na pewno chcesz zadzwonić na numer alarmowy?", phone: "112")
        self.present(alert, animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return callsTitle.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellPatientCall", for: indexPath) as! CellPatientCall
        
        cell.callTitle.text = callsTitle[indexPath.item]
        cell.callImage.image = callsImage[indexPath.item]
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("kliknięta potrzeba \(callsTitle[indexPath.item])")
        let cell = collectionView.cellForItem(at: indexPath)
        
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 5, options: [],
            animations: {
                cell!.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: {
                        cell!.transform = CGAffineTransform(scaleX: 1, y: 1)
                    }, completion: nil
                )
                                    
            }
        )
        
        if self.caregiverPhoneButton.isHidden == true {
            let alert = UIAlertController(title: "Uwaga", message: "Brak wybranego aktywnego opiekuna. Aby wysłać potrzebę należy najpierw wybrać aktywnego opiekuna.", preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
        else {
            sendCallId = indexPath.item
            sendCaregiverId = Int(self.idActiveCaregiver)
            sendPatientId = Int(self.idPatient)
            
            performSegue(withIdentifier: "showSend", sender: self)
        }
        
    }
    
    override func viewDidLayoutSubviews() {
        caregiverButton.setWhiteButton()
        caregiverPhoneButton.setCircleButton()
        alarmPhoneButton.setCircleButton()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        loadLoginUserDataFromCoreData()
        loadDataActiveCaregiver()
        navBarButtons()
        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)
    }
    
    // MARK: - Navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showSend" {
            let vc = segue.destination as! SendViewController
            vc.callId = sendCallId
            vc.idPatient = sendPatientId
            vc.idCaregiver = sendCaregiverId
        }
    }
}
