//
//  LoginViewController.swift
//  Kalker

import UIKit
import CoreData
import Alamofire
import SwiftyJSON
import Firebase
import FirebaseMessaging

class LoginViewController: UIViewController {

    var typeAccount: Int!
    var avatarImage: UIImage!
    var managedObjectContext: NSManagedObjectContext!
    var loginUser = [User]()
    
    @IBOutlet weak var loginButton: UIButton!
    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    
    @IBOutlet weak var labelRegisterOutlet: UILabel!
    @IBOutlet weak var registerButtonOutlet: UIButton!
    @IBOutlet weak var forgotButtonOutlet: UIButton!
    
    // Pokaż/Ukryj klawiaturę podczas edycji
    @objc func keyboardWillShow(notification: NSNotification) {
        let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
        if self.view.frame.origin.y == 0 {
            self.view.frame.origin.y -= (keyboardSize?.height)!
        }
    }
    @objc func keyboardWillHide(notification: NSNotification) {
        self.view.frame.origin.y = 0
    }
    func registerKeyboardEvents() {
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    func deregisterKeyboardEvents() {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window)
    }
    // End
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        emailTextField.isHidden = true
        passwordTextField.isHidden = true
        loginButton.isHidden = true
        labelRegisterOutlet.isHidden = true
        registerButtonOutlet.isHidden = true
        forgotButtonOutlet.isHidden = true
        
        registerKeyboardEvents()
        self.hideKeyboardWhenTappedAround()
        
        setDefaultBackground(viewForBackground: self.view)
        navigationItem.setHidesBackButton(true, animated:true)
        
        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        
        do {
            // Sprawdzenie czy jest ktoś zalogowany
            let fetchRequest: NSFetchRequest<User> = User.fetchRequest()
            let isLogin = try managedObjectContext.count(for: fetchRequest)
            
            print("isLogin", isLogin)
            
            if isLogin > 0 {
                do {
                    loginUser = try managedObjectContext.fetch(fetchRequest)
                    typeAccount = Int((loginUser.first?.type)!)
                    
                    if typeAccount == 2 {
                        let storyboard = UIStoryboard(name: "Main", bundle: nil)
                        let vc = storyboard.instantiateViewController(withIdentifier: "loginCaregiver") as! CaregiverCallsViewController
                        navigationController?.pushViewController(vc, animated: true)
                    }
                    else {
                        let storyboard = UIStoryboard(name: "Main", bundle: nil)
                        let vc = storyboard.instantiateViewController(withIdentifier: "loginPatient") as! PatientCallsViewController
                        navigationController?.pushViewController(vc, animated: true)
                    }
                    
                } catch {
                    print("Błąd podczas ładowania informacji o użytkowniku \(error.localizedDescription)")
                }
            }
            else {
                // Pokaż elementy
                emailTextField.isHidden = false
                passwordTextField.isHidden = false
                loginButton.isHidden = false
                labelRegisterOutlet.isHidden = false
                registerButtonOutlet.isHidden = false
                forgotButtonOutlet.isHidden = false
            }
            
        } catch {
            print("error")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewDidLayoutSubviews() {
        loginButton.setWhiteButton()
        emailTextField.setDefaultTextField()
        passwordTextField.setDefaultTextField()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        setTransparentNavigationBar(navBar: self.navigationController!)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        deregisterKeyboardEvents()
    }
    
    @IBAction func login(_ sender: UIButton) {
        clickAnimation(button: loginButton)
        
        if emailTextField.text != "" && passwordTextField.text != "" {
            if isValidEmail(email: emailTextField.text!) {
                let tmpToken = Messaging.messaging().fcmToken!
                let parameters: Parameters = ["token": tmpToken,
                                              "email": emailTextField.text!,
                                              "password": passwordTextField.text!
                ]
                
                Alamofire.request("https://kalkerapp.pl/api/login.php", method: .post, parameters: parameters)
                    .responseJSON { response in
                        if let jsonData = response.result.value {
                            let json = JSON(jsonData)
                            if json[0]["id"] == 0 {
                                let alert = setAlert(title: "Kalker", message: "Brak użytkownika w bazie")
                                self.present(alert, animated: true, completion: nil)
                            }
                            else {
                                self.saveUserDataToCoreData(json: json)
                            }
                        }
                }
            }
            else{
                let alert = setAlert(title: "Kalker", message: "Format adresu e-mail jest niepoprawny")
                self.present(alert, animated: true, completion: nil)
            }
        }
        else {
            let alert = setAlert(title: "Kalker", message: "Wypełnij wymagane pola")
            self.present(alert, animated: true, completion: nil)
        }
        
    }
    
    func saveUserDataToCoreData(json: JSON) {
        let saveUser = User(context: managedObjectContext)
        var tmpAvatarString: URL!
        
        if (json[0]["tokenConnection"].null != nil) {
            typeAccount = 2
            saveUser.activeCaregiver = 0
            tmpAvatarString = URL(string: "https://kalkerapp.pl/avatar/c/\(json[0]["avatar"])")
        }
        else {
            typeAccount = 1
            saveUser.activeCaregiver = Int32(json[0]["activeCaregiver"].string!)!
            tmpAvatarString = URL(string: "https://kalkerapp.pl/avatar/p/\(json[0]["avatar"])")
        }
        
        if json[0]["avatar"].string! == "" {
            self.avatarImage = UIImage(named: "avatarDefault")
        }
        else {
            let data = try? Data(contentsOf: tmpAvatarString!)
            self.avatarImage = UIImage(data: data!)
        }
        
        saveUser.type = Int16(typeAccount)
        saveUser.id = Int32(json[0]["id"].string!)!
        saveUser.name = json[0]["name"].string
        saveUser.email = json[0]["email"].string
        saveUser.password = json[0]["password"].string
        saveUser.avatar = NSData(data: UIImageJPEGRepresentation(self.avatarImage, 0.3)!) as Data
        saveUser.phone = json[0]["phone"].string
        saveUser.birth = json[0]["birth"].string
        saveUser.desc = json[0]["description"].string
        saveUser.tokenAndroid = ""
        saveUser.tokenIOS = Messaging.messaging().fcmToken!
        saveUser.tokenConnection = json[0]["tokenConnection"].string
        saveUser.isLogin = true
        
        do {
            try self.managedObjectContext.save()
            // Przejście do logowania
            if typeAccount == 2 {
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let vc = storyboard.instantiateViewController(withIdentifier: "loginCaregiver") as! CaregiverCallsViewController
                navigationController?.pushViewController(vc, animated: true)
            }
            else {
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let vc = storyboard.instantiateViewController(withIdentifier: "loginPatient") as! PatientCallsViewController
                navigationController?.pushViewController(vc, animated: true)
            }
            
        } catch {
            print("Błąd podczas rejestracji użytkownika \(error.localizedDescription)")
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
