//
//  SettingsViewController.swift
//  Kalker

import UIKit
import CoreData
import Alamofire
import SwiftyJSON

class SettingsViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, SendProfileData {

    var managedObjectContext: NSManagedObjectContext!
    var loginUser = [User]()
    var idUser: Int32!
    var passwordUser: String!
    var isAvatar: Bool = false
    var typeAccount: Int!
    let imagePickerController = UIImagePickerController()
    
    @IBOutlet weak var avatar: UIImageView!
    @IBOutlet weak var saveButton: UIButton!
    @IBOutlet weak var logoutButton: UIButton!
    @IBOutlet weak var showTokenButton: UIButton!
    
    // Zapis danych z TableView
    var saveName: String!
    var saveEmail: String!
    
    var saveOldPassword: String!
    var saveNewPassword: String!
    
    var savePhone: String!
    var saveDate: String!
    var saveDescription: String!
    
    func nameData(data: String) {
        saveName = data
    }
    func emailData(data: String) {
        saveEmail = data
    }
    
    func oldPasswordData(data: String) {
        saveOldPassword = data
    }
    func newPasswordData(data: String) {
        saveNewPassword = data
    }
    
    func phoneData(data: String) {
        savePhone = data
    }
    func dateData(data: String) {
        saveDate = data
    }
    func descriptionData(data: String) {
        saveDescription = data
    }
    //
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.hideKeyboardWhenTappedAround()
        setDefaultBackground(viewForBackground: self.view)
        
        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        loadLoginUserDataFromCoreData()
        
        imagePickerController.delegate = self
        imagePickerController.sourceType = .photoLibrary
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(avatarTapped))
        avatar.isUserInteractionEnabled = true
        avatar.addGestureRecognizer(tapGestureRecognizer)
        
        if typeAccount == 2 {
            showTokenButton.isHidden = true
        }
    }
    
    @objc func avatarTapped() {
        clickAnimationImage(image: avatar)
        
        self.present(imagePickerController, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        avatar.image = image
        isAvatar = true
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    @IBAction func clickTokenButton(_ sender: UIButton) {
        clickAnimation(button: showTokenButton)
    }
    
    @IBAction func logout(_ sender: UIButton) {
        clickAnimation(button: logoutButton)
        let parameters: Parameters = ["id": idUser!,
                                      "type": typeAccount!
        ]
        
        Alamofire.request("https://kalkerapp.pl/api/logout.php", method: .post, parameters: parameters)
            .responseJSON { response in
                if let jsonData = response.result.value {
                    let json = JSON(jsonData)
                    
                    let fetchRequest: NSFetchRequest<User> = User.fetchRequest()
                    //fetchRequest.predicate = NSPredicate(format: "isLogin == %@", NSNumber(booleanLiteral: true))
                    
                    if let result = try? self.managedObjectContext.fetch(fetchRequest) {
                        for object in result {
                            self.managedObjectContext.delete(object)
                        }
                    }
                    self.backToLoginView()
                }
        }
    }
    
    @IBAction func saveProfile(_ sender: UIButton) {
        clickAnimation(button: saveButton)
        let parameters: Parameters!
        var tmp = 1
        
        print("WPISANE: \(saveOldPassword!)")
        print("COREDATA: \(passwordUser!)")
        
        if saveOldPassword != "" && saveNewPassword != "" {
            if saveOldPassword == saveNewPassword {
                tmp = 0
                let alert = setAlert(title: "Kalker", message: "Nowe hasło nie może być identyczne jak aktualne")
                self.present(alert, animated: true, completion: nil)
            }
            
            if saveOldPassword == passwordUser {
                tmp = 0
                let alert = setAlert(title: "Kalker", message: "Aktualne hasło nie jest poprawne")
                self.present(alert, animated: true, completion: nil)
            }
            
            if (tmp == 1) {
                print("zmieniam hasło")
                parameters = ["id": idUser!,
                              "name": saveName,
                              "email": saveEmail,
                              "password": saveNewPassword,
                              "phone": savePhone,
                              "birth": saveDate,
                              "description": saveDescription]
                
                Alamofire.request("https://kalkerapp.pl/api/edit.php", method: .post, parameters: parameters)
                    .responseJSON { response in
                        if let jsonData = response.result.value {
                            let json = JSON(jsonData)
                            print(json)
                            
                            if self.isAvatar == true {
                                self.uploadAvatar()
                            }
                            
                            self.saveToCoreDataWithPassword()
                            
                            if json[0]["id"] == 1 {
                                let alert = setAlert(title: "Sukces", message: "Edycja profilu zakończona sukcesem")
                                self.present(alert, animated: true, completion: nil)
                            }
                            else if json[0]["id"] == 2 {
                                let alert = setAlert(title: "Uwaga", message: "Adres e-mail występuje już w bazie, więc jego zmiana nie była możliwa")
                                self.present(alert, animated: true, completion: nil)
                            }
                        }
                }
            }
        }
        else if saveOldPassword == "" && saveNewPassword == "" {
            print("nie zmianiam hasła")
            parameters = ["id": idUser!,
                          "name": saveName,
                          "email": saveEmail,
                          "phone": savePhone,
                          "birth": saveDate,
                          "description": saveDescription]
            
            Alamofire.request("https://kalkerapp.pl/api/edit.php", method: .post, parameters: parameters)
                .responseJSON { response in
                    if let jsonData = response.result.value {
                        let json = JSON(jsonData)
                        print(json)
                        
                        if self.isAvatar == true {
                            self.uploadAvatar()
                        }
                        
                        self.saveToCoreData()
                        
                        if json[0]["id"] == 1 {
                            let alert = setAlert(title: "Sukces", message: "Edycja profilu zakończona sukcesem")
                            self.present(alert, animated: true, completion: nil)
                        }
                        else if json[0]["id"] == 2 {
                            let alert = setAlert(title: "Uwaga", message: "Adres e-mail występuje już w bazie więc jego zmiana nie była możliwa")
                            self.present(alert, animated: true, completion: nil)
                        }
                    }
            }
        }
        else {
            print("alert")
            let alert = setAlert(title: "Kalker", message: "Aby zmienić hasło należy uzupełnić wszystkie wymagane pola")
            self.present(alert, animated: true, completion: nil)
        }
    }
    
    func uploadAvatar() {
        let param = ["id": "\(self.idUser!)", "type": "\(self.typeAccount!)"]
        let image = self.avatar.image?.resizeImageWith(newSize: CGSize(width: 200, height: 200))
        let imgData = UIImageJPEGRepresentation(image!, 0.2)!
        let url = "https://kalkerapp.pl/avatar/upload.php"
        
        Alamofire.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(imgData, withName: "avatar", fileName: "\(self.idUser!).jpg", mimeType: "image/jpeg")
                for (key, val) in param {
                    multipartFormData.append(val.data(using: String.Encoding.utf8)!, withName: key)
                }
        },
            to: url,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        if let jsonResponse = response.result.value {
                            print(jsonResponse)
                        }
                    }
                case .failure(let encodingError):
                    print(encodingError)
                }
        })
    }
    
    func saveToCoreData() {
        // Zapis do CoreData
        let fetchRequest: NSFetchRequest<User> = User.fetchRequest()
        
        do {
            let array_users = try managedObjectContext.fetch(fetchRequest)
            let user = array_users[0]
            
            if isAvatar == true {
                user.setValue(NSData(data: UIImageJPEGRepresentation(self.avatar.image!, 0.3)!), forKey: "avatar")
            }
            
            user.setValue(saveName, forKey: "name")
            user.setValue(saveEmail, forKey: "email")
            
            user.setValue(savePhone, forKey: "phone")
            user.setValue(saveDate, forKey: "birth")
            user.setValue(saveDescription, forKey: "desc")
            
            do {
                try self.managedObjectContext.save()
            } catch {
                print("Błąd podczas zapisu aktywnego opiekuna \(error.localizedDescription)")
            }
        } catch {
            print("Błąd podczas wysłania zapytania zapisu \(error.localizedDescription)")
        }
        //
        loadLoginUserDataFromCoreData()
    }
    func saveToCoreDataWithPassword() {
        // Zapis do CoreData
        let fetchRequest: NSFetchRequest<User> = User.fetchRequest()
        
        do {
            let array_users = try managedObjectContext.fetch(fetchRequest)
            let user = array_users[0]
            
            if isAvatar == true {
                user.setValue(NSData(data: UIImageJPEGRepresentation(self.avatar.image!, 0.3)!), forKey: "avatar")
            }
            
            user.setValue(saveName, forKey: "name")
            user.setValue(saveEmail, forKey: "email")
            
            user.setValue(saveNewPassword, forKey: "password")
            
            user.setValue(savePhone, forKey: "phone")
            user.setValue(saveDate, forKey: "birth")
            user.setValue(saveDescription, forKey: "desc")
            
            do {
                try self.managedObjectContext.save()
            } catch {
                print("Błąd podczas zapisu aktywnego opiekuna \(error.localizedDescription)")
            }
        } catch {
            print("Błąd podczas wysłania zapytania zapisu \(error.localizedDescription)")
        }
        //
        loadLoginUserDataFromCoreData()
    }
    
    func backToLoginView() {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "loginView") as! LoginViewController
        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)
            if loginUser.first?.avatar == nil {
                avatar.image = UIImage(named: "avatarDefault")
            }
            else {
                avatar.image = UIImage(data: (loginUser.first?.avatar)! as Data)
            }
            idUser = loginUser.first?.id
            passwordUser = loginUser.first?.password
            typeAccount = Int((loginUser.first?.type)!)
            
        } catch {
            print("Błąd podczas ładowania informacji o użytkowniku \(error.localizedDescription)")
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewDidLayoutSubviews() {
        saveButton.setWhiteButton()
        logoutButton.setWhiteButton()
        showTokenButton.setWhiteButton()
        avatar.setRoundImage()
        avatar.setBorderImage()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        setTransparentNavigationBar(navBar: self.navigationController!)
        
        NotificationCenter.default.addObserver(self, selector: #selector(observeNotification(notification:)), name: Notification.Name("SendCaregiverNotif"), object: nil)
        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("SendCaregiverNotif"), object: nil)
        NotificationCenter.default.removeObserver(self, name: Notification.Name("SendPatientNotif"), 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)
    }
    
    @objc func observeNotificationPatient(notification: Notification) {
        // Open PatientView
        let alert = setNotifForPatient(title: "Odpowiedź opiekuna", message: "Będę za 5 minut", navcontroller: navigationController!)
        self.present(alert, animated: true, completion: nil)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "infoEditProfile" {
            let vc: SettingsTableViewController = segue.destination as! SettingsTableViewController
            vc.delegate = self
        }
    }

}
