//
//  RegisterStepTwoViewController.swift
//  Kalker

// typeAccount:
// 1 - Patient
// 2 - Caregiver

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

class RegisterStepTwoViewController: UIViewController, UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    var typeAccount: Int!
    var avatarImage: UIImage!
    var name: String!
    var email: String!
    var password: String!
    var tokenIOS: String!
    var isAvatar: Bool = false
    let imagePickerController = UIImagePickerController()
    
    var managedObjectContext: NSManagedObjectContext!
    
    var datePicker = UIDatePicker()
    let formatter = DateFormatter()
    
    @IBOutlet weak var avatarImageView: UIImageView!
    @IBOutlet weak var phoneTextField: UITextField!
    @IBOutlet weak var birthTextField: UITextField!
    @IBOutlet weak var descriptionTextView: UITextView!
    
    @IBOutlet weak var registerButton: 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()
        registerKeyboardEvents()
        self.hideKeyboardWhenTappedAround()
        
        setDefaultBackground(viewForBackground: self.view)
        
        descriptionTextView.delegate = self
        descriptionTextView.setPlaceholder()
        
        if typeAccount == 2 {
            birthTextField.isHidden = true
            descriptionTextView.isHidden = true
        }
        
        tokenIOS = Messaging.messaging().fcmToken!
        
        imagePickerController.delegate = self
        imagePickerController.sourceType = .photoLibrary
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(avatarTapped))
        avatarImageView.isUserInteractionEnabled = true
        avatarImageView.addGestureRecognizer(tapGestureRecognizer)
        
        createDatePicker()
        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    }
    
    @objc func avatarTapped() {
        clickAnimationImage(image: avatarImageView)
        
        self.present(imagePickerController, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        avatarImageView.image = image
        isAvatar = true
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func createDatePicker() {
        datePicker.datePickerMode = .date
        datePicker.locale = Locale.init(identifier: "pl_PL")
        let toolbar = UIToolbar()
        toolbar.sizeToFit()
        
        let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(datePickerTapped))
        toolbar.setItems([doneButton], animated: true)
        
        formatter.dateFormat = "dd.MM.yyyy"
        
        birthTextField.inputAccessoryView = toolbar
        birthTextField.inputView = datePicker
    }
    
    @objc func datePickerTapped() {
        birthTextField.text = formatter.string(from: datePicker.date)
        self.view.endEditing(true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func textViewDidChange(_ textView: UITextView) {
        descriptionTextView.checkPlaceholder()
    }
    
    override func viewDidLayoutSubviews() {
        registerButton.setWhiteButton()
        phoneTextField.setDefaultTextField()
        avatarImageView.setRoundImage()
        avatarImageView.setBorderImage()
        
        if typeAccount == 1 {
            birthTextField.setDefaultTextField()
            descriptionTextView.addBottomBorderWithColor()
        }
    }
    
    @IBAction func register(_ sender: UIButton) {
        clickAnimation(button: registerButton)
        
        var tmpChecker = false
        
        if typeAccount == 1 {
            if phoneTextField.text != "" && birthTextField.text != "" {
                tmpChecker = true
            }
        }
        else {
            if phoneTextField.text != "" {
                tmpChecker = true
            }
        }

        if tmpChecker == true {
            let parameters: Parameters!
            
            if typeAccount == 1 {
                parameters = ["type": typeAccount,
                              "name": name,
                              "email": email,
                              "password": password,
                              "phone": phoneTextField.text!,
                              "avatar": "",
                              "token": tokenIOS,
                              "birth": birthTextField.text!,
                              "description": descriptionTextView.text!]
            } else {
                parameters = ["type": typeAccount,
                              "name": name,
                              "email": email,
                              "password": password,
                              "phone": phoneTextField.text!,
                              "avatar": "",
                              "token": tokenIOS]
            }
            
            
            Alamofire.request("https://kalkerapp.pl/api/register.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: "Konto z podanym adresem e-mail już istnieje")
                            self.present(alert, animated: true, completion: nil)
                        }
                        else {
                            if self.isAvatar == true {
                                // Upload avatar
                                let param = ["id": json[0]["id"].string!, "type": "\(self.typeAccount!)"]
                                let image = self.avatarImageView.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: "\(json[0]["id"]).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)
                                    }
                                })
                                // Upload avatar
                            }
                            self.saveUserDataToCoreData(json: json)
                        }
                        
                    }
            }
        } 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 tmpAvatarType: String!
        
        if (json[0]["tokenConnection"].null != nil) {
            typeAccount = 2
            saveUser.activeCaregiver = 0
            //tmpAvatarType = "c"
        }
        else {
            typeAccount = 1
            saveUser.activeCaregiver = Int32(json[0]["activeCaregiver"].string!)!
            //tmpAvatarType = "p"
        }
        
        if isAvatar == false {
            self.avatarImage = UIImage(named: "avatarDefault")
        }
        else {
            self.avatarImage = self.avatarImageView.image
        }
        
        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)")
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        setTransparentNavigationBar(navBar: self.navigationController!)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        deregisterKeyboardEvents()
    }
}
