//
//  SettingsTableViewController.swift
//  Kalker

import UIKit
import CoreData

protocol SendProfileData {
    func nameData(data: String)
    func emailData(data: String)
   
    func oldPasswordData(data: String)
    func newPasswordData(data: String)
    
    func phoneData(data: String)
    func dateData(data: String)
    func descriptionData(data: String)
}

class SettingsTableViewController: UITableViewController {

    var delegate: SendProfileData? = nil
    
    @IBOutlet weak var birthCell: UITableViewCell!
    @IBOutlet weak var descriptionCell: UITableViewCell!
    
    var managedObjectContext: NSManagedObjectContext!
    var loginUser = [User]()
    
    var datePicker = UIDatePicker()
    let formatter = DateFormatter()
    
    @IBOutlet weak var nameTextField: UITextField!
    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var oldPasswordTextField: UITextField!
    @IBOutlet weak var newPasswordTextField: UITextField!
    @IBOutlet weak var phoneTextField: UITextField!
    @IBOutlet weak var dateTextField: UITextField!
    @IBOutlet weak var descriptionTextField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.hideKeyboardWhenTappedAround()
        createDatePicker()
        
        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        loadLoginUserDataFromCoreData()
        
        delegate?.nameData(data: nameTextField.text!)
        delegate?.emailData(data: emailTextField.text!)
        delegate?.oldPasswordData(data: oldPasswordTextField.text!)
        delegate?.newPasswordData(data: newPasswordTextField.text!)
        delegate?.phoneData(data: phoneTextField.text!)
        delegate?.dateData(data: dateTextField.text!)
        delegate?.descriptionData(data: descriptionTextField.text!)
    }
    
    @IBAction func sendName(_ sender: UITextField) {
        if delegate != nil {
            if nameTextField.text != nil {
                let data = nameTextField.text
                delegate?.nameData(data: data!)
            }
        }
    }
    
    @IBAction func sendEmail(_ sender: UITextField) {
        if delegate != nil {
            if emailTextField.text != nil {
                let data = emailTextField.text
                delegate?.emailData(data: data!)
            }
        }
    }
    
    @IBAction func sendOldPassword(_ sender: UITextField) {
        if delegate != nil {
            if oldPasswordTextField.text != nil {
                let data = oldPasswordTextField.text
                delegate?.oldPasswordData(data: data!)
            }
        }
    }
    
    @IBAction func sendNewPassword(_ sender: UITextField) {
        if delegate != nil {
            if newPasswordTextField.text != nil {
                let data = newPasswordTextField.text
                delegate?.newPasswordData(data: data!)
            }
        }
    }
    
    @IBAction func sendPhone(_ sender: UITextField) {
        if delegate != nil {
            if phoneTextField.text != nil {
                let data = phoneTextField.text
                delegate?.phoneData(data: data!)
            }
        }
    }
    
    @IBAction func sendDate(_ sender: UITextField) {
        if delegate != nil {
            if dateTextField.text != nil {
                let data = dateTextField.text
                delegate?.dateData(data: data!)
            }
        }
    }
    
    @IBAction func sendDescription(_ sender: UITextField) {
        if delegate != nil {
            if descriptionTextField.text != nil {
                let data = descriptionTextField.text
                delegate?.descriptionData(data: data!)
            }
        }
    }
    
    func loadLoginUserDataFromCoreData() {
        let fetchRequest: NSFetchRequest<User> = User.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "isLogin == %@", NSNumber(booleanLiteral: true))
        
        do {
            loginUser = try managedObjectContext.fetch(fetchRequest)
            nameTextField.text = loginUser.first?.name
            emailTextField.text = loginUser.first?.email
            phoneTextField.text = loginUser.first?.phone
            
            if loginUser.first?.type == 1 {
                dateTextField.text = loginUser.first?.birth
                descriptionTextField.text = loginUser.first?.desc
            }
            else {
                birthCell.isHidden = true
                descriptionCell.isHidden = true
            }
            
            
        } catch {
            print("Błąd podczas ładowania informacji o użytkowniku \(error.localizedDescription)")
        }
    }
    
    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"
        
        dateTextField.inputAccessoryView = toolbar
        dateTextField.inputView = datePicker
    }
    
    @objc func datePickerTapped() {
        dateTextField.text = formatter.string(from: datePicker.date)
        self.view.endEditing(true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
