//
//  PatientStoryViewController.swift
//  Kalker

import UIKit
import CoreData
import Alamofire
import SwiftyJSON

class PatientStoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var managedObjectContext: NSManagedObjectContext!
    var loginUser = [User]()
    var avatar: UIImage!
    var idPatient: Int!
    var json: JSON!
    var rowCount = 0
    
    let callsTitle = Call.getCallTitle()
    let callsImage = Call.getCallImage()
    
    var callStoryId: [Int] = []
    var callStoryTime: [String] = []
    var formatter = DateFormatter()
    
    @IBOutlet weak var storyTableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setDefaultBackground(viewForBackground: self.view)
        storyTableView.backgroundColor = UIColor.clear
        
        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        loadLoginUserDataFromCoreData()
        
        loadCallStory()
        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)
            avatar = UIImage(data: (loginUser.first?.avatar)! as Data)
            
        } catch {
            print("Błąd podczas ładowania informacji o użytkowniku \(error.localizedDescription)")
        }
    }
    
    func loadCallStory() {
        self.callStoryId.removeAll()
        self.callStoryTime.removeAll()
        
        let parameters: Parameters = ["idPatient": idPatient!]
        
        Alamofire.request("https://kalkerapp.pl/api/story.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.callStoryId.append(Int(self.json[i]["idCall"].string!)!)
                        self.callStoryTime.append(self.json[i]["date"].string!)
                        
                    }
                    
                    DispatchQueue.main.async() {
                        self.storyTableView.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 = storyTableView.dequeueReusableCell(withIdentifier: "cellStory") as? CellPatientStory
        
        cell?.callLabel.text = self.callsTitle[self.callStoryId[indexPath.row]-1]
        cell?.callImage.image = self.callsImage[self.callStoryId[indexPath.row]-1]

        formatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ss"
        let tmpDate = formatter.date(from: self.callStoryTime[indexPath.row])
        cell?.dateTime.text = String(describing: DateFormatter.localizedString(from: tmpDate!, dateStyle: .short, timeStyle: .short))
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        storyTableView.deselectRow(at: indexPath, animated: true)
    }
    
    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)
    }
    
    @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)
    }
}
