//
//  CaregiverCallsViewController.swift
//  Kalker

import UIKit
import CoreData
import Alamofire
import SwiftyJSON
import SDWebImage
import Firebase
import AVFoundation

class CaregiverCallsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, ResetList {

    var managedObjectContext: NSManagedObjectContext!
    var loginUser = [User]()
    var avatar: UIImage!
    var idCaregiver: Int!
    var json: JSON!
    var rowCount = 0
    var idLast = 0
    
    let callsTitle = Call.getCallTitle()
    let callsImage = Call.getCallImage()
    
    var rowID: [Int] = []
    var callsID: [Int] = []
    var callsPatientId: [Int] = []
    var callsPatient: [String] = []
    var callsPatientAvatar: [String] = []
    var callsPatientPhone: [String] = []
    var callsTime: [String] = []
    
    var now = Date()
    var timer = Timer()
    
    var popupName: String!
    var popupAvatar: UIImage!
    var popupCallId: Int!
    var popupRowId: Int!
    var popupPatientId: Int!
    var popupPhone: String!
    
    var indicator: UIActivityIndicatorView = UIActivityIndicatorView()
    
    @IBOutlet weak var callsTableView: UITableView!
    
    func idLastReset(data: Int) {
        self.idLast = data
        loadCalls()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setDefaultBackground(viewForBackground: self.view)
        callsTableView.backgroundColor = UIColor.clear
        
        indicator.center = self.view.center
        indicator.hidesWhenStopped = true
        indicator.activityIndicatorViewStyle = .whiteLarge
        self.view.addSubview(indicator)
        
        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)
        
        // Przycisk listy pacjentów
        let buttonListPatient = buttonInNavigationBar(img: UIImage.init(named: "patientIcon")!)
        buttonListPatient.addTarget(self, action: #selector(openListPatient), for: .touchUpInside)
        let barButton2 = UIBarButtonItem.init(customView: buttonListPatient)
        
        navigationItem.setRightBarButtonItems([barButton, barButton2], animated: false)
        
        // Przycisk odświeżania
        let buttonReload = buttonInNavigationBar(img: UIImage.init(named: "reloadIcon")!)
        buttonReload.addTarget(self, action: #selector(loadCalls), for: .touchUpInside)
        let barButton3 = UIBarButtonItem.init(customView: buttonReload)
        
        navigationItem.setLeftBarButtonItems([barButton3], 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)
    }
    
    @objc func openListPatient(sender: UIBarButtonItem) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "patientList") as! ListPatientViewController
        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 = Int((loginUser.first?.id)!)
            avatar = UIImage(data: (loginUser.first?.avatar)! as Data)
            
        } catch {
            print("Błąd podczas ładowania informacji o użytkowniku \(error.localizedDescription)")
        }
    }
    
    @objc func loadCallsFromNotif(notification: Notification){
        let systemSoundID: SystemSoundID = 1301
        AudioServicesPlaySystemSound(systemSoundID)
        loadCalls()
    }
    
    @objc func loadCalls() {
        indicator.startAnimating()
        print("start loading")
        
        if self.idLast == 0 {
            rowID.removeAll()
            callsID.removeAll()
            callsPatientId.removeAll()
            callsPatient.removeAll()
            callsPatientAvatar.removeAll()
            callsPatientPhone.removeAll()
            callsTime.removeAll()
        }
        
        let parameters = ["idCaregiver": idCaregiver!,
                          "idLast": idLast]
        
        Alamofire.request("https://kalkerapp.pl/api/activeCalls.php", method: .post, parameters: parameters)
            .responseJSON { response in
                if let jsonData = response.result.value {
                    self.json = JSON(jsonData)
                    //print(self.json)
                    
                    for i in 0..<self.json.count {
                        self.rowID.insert(Int(self.json[i]["id"].string!)!, at: 0)
                        self.callsID.insert(Int(self.json[i]["idCall"].string!)!, at: 0)
                        self.callsPatientId.insert(Int(self.json[i]["idPatient"].string!)!, at: 0)
                        self.callsPatient.insert(self.json[i]["name"].string!, at: 0)
                        self.callsTime.insert(self.json[i]["date"].string!, at: 0)
                        self.callsPatientAvatar.insert(self.json[i]["avatar"].string!, at: 0)
                        self.callsPatientPhone.insert(self.json[i]["phone"].string!, at: 0)
                    }
                    
                    self.rowCount = self.callsID.count
                    
                    if self.json.count != 0 {
                        self.idLast = Int(self.json[self.json.count-1]["id"].string!)!
                        self.callsTableView.reloadData()
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            self.callsTableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
                        }
                    }
                }
        }
        
        indicator.stopAnimating()
        print("stop loading")
    }

    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 = self.callsTableView.dequeueReusableCell(withIdentifier: "cellCaregiverCall") as? CellCaregiverCall
        
        cell?.contentView.bounds.size.width = tableView.bounds.width
        
        DispatchQueue.main.async(execute: { () -> Void in
            cell?.call.text = self.callsTitle[self.callsID[indexPath.row]-1]
            cell?.callImage.image = self.callsImage[self.callsID[indexPath.row]-1]
            cell?.name.text = self.callsPatient[indexPath.row]
            
            
            if self.callsPatientAvatar[indexPath.row] == "" {
                cell?.avatar.image = UIImage(named: "avatarDefault")
            }
            else {
                cell?.avatar.sd_setImage(with: URL(string: "https://kalkerapp.pl/avatar/p/\(self.callsPatientAvatar[indexPath.row])"), placeholderImage: UIImage(named: "avatarDefault"))
            }
            
            self.timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: (#selector(self.updateTimer)), userInfo: nil, repeats: true)
            
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ss"
            let dateString = self.callsTime[indexPath.row] // Data z bazy
            let tmpDate = dateFormatter.date(from: dateString)
            
            cell?.time.text = tmpDate!.timeAgo(startDate: self.now)
        })

        return cell!
    }
    
    @objc func updateTimer() {
        self.now = Date()
        callsTableView.reloadData()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell: CellCaregiverCall = callsTableView.cellForRow(at: indexPath) as! CellCaregiverCall
        
        popupRowId = self.rowID[indexPath.row]
        popupCallId = self.callsID[indexPath.row] - 1
        popupPatientId = self.callsPatientId[indexPath.row]
        popupName = self.callsPatient[indexPath.row]
        popupAvatar = cell.avatar.image
        popupPhone = self.callsPatientPhone[indexPath.row]
        
        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
                )
            }
        )
        
        performSegue(withIdentifier: "showReply", sender: self)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        loadCalls()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        setTransparentNavigationBar(navBar: self.navigationController!)
        loadLoginUserDataFromCoreData()
        navBarButtons()
        NotificationCenter.default.addObserver(self, selector: #selector(loadCallsFromNotif(notification:)), name: Notification.Name("SendCaregiverNotif"), object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(self, name: Notification.Name("SendCaregiverNotif"), object: nil)
    }
    
    // MARK: - Navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showReply" {
            let vc = segue.destination as! ReplyViewController
            vc.name = popupName
            vc.avatar = popupAvatar
            vc.callId = popupCallId
            vc.rowId = popupRowId
            vc.patientId = popupPatientId
            vc.patientPhone = popupPhone
            vc.caregiverId = idCaregiver
            vc.delegate = self
        }
    }
}
