//
//  AddDocumentViewController.swift
//  iPOS
//
//  Created by Apple iMac on 12/07/2017.
//  Copyright © 2017 BBC. All rights reserved.
//

import Foundation
class AddDocumentViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate, UIPopoverPresentationControllerDelegate{
    
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var tfDocumentName: UITextField!
    @IBOutlet weak var tfDocumentType: UITextField!
    @IBOutlet weak var saveButton: UIBarButtonItem!
    
    var contactId: String?
    var documentTypeId: Int? = nil
    let imageMaxLength: CGFloat = 800
    var documentTypes: [DocumentType] = [DocumentType]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tfDocumentName.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        view.addGestureRecognizer(tap)
        if State.documentTypes == nil{
            loadDocumentTypes()
        }
        else{
            documentTypes = State.documentTypes!
        }
        delegateTextField()
        createLeftBackButton()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        checkRequiredData()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    func createLeftBackButton(){
        let backButton = UIBarButtonItem(title: Util.getString("Cancel"), style: .done, target: self, action: #selector(backButtonPressed))
        self.navigationItem.leftBarButtonItem = backButton
        self.navigationItem.leftItemsSupplementBackButton = false
    }
    
    @objc func backButtonPressed(){
        if self.saveButton.isEnabled{
            Util.AlertYesNo(viewController: self, title: "iPOS", message: Util.getString("Are you sure you want to cancel? All changes will be lost!"), actionYes: {
                _ = self.navigationController?.popViewController(animated: true)
            }, actionNo: {
                return
            })
        }
        else{
            _ = self.navigationController?.popViewController(animated: true)
        }
    }
    
    @IBAction func cameraButton_Click(_ sender: Any) {
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .camera
            imagePicker.allowsEditing = false
            self.present(imagePicker, animated: true, completion: nil)
        }
    }
    
    @IBAction func galleryButton_Click(_ sender: Any) {
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .photoLibrary
            imagePicker.allowsEditing = true
            self.present(imagePicker, animated: true, completion: nil)
        }
    }
    
    @IBAction func saveButton_Click(_ sender: Any) {
        let attachment = createAttachment()
        State.saveAttachments(attachment: attachment) { (result) in
            if result{
                _ = self.navigationController?.popViewController(animated: true)
            }
            else{
                Util.GeneralAlert(viewController: self, message: Util.getString("An error has occured.\nPlease try again!"))
            }
        }
    }
    
    func loadDocumentTypes(){
        State.loadDocumentTypes { (result) in
            if !result{
                Util.GeneralAlert(viewController: self, message: Util.getString("An error has occured.\nPlease try again!"))
                _ = self.navigationController?.popViewController(animated: true)
            }
            else{
                self.documentTypes = State.documentTypes!
            }
        }
    }
    
    func createAttachment() -> Attachment{
        let attachment = Attachment()
        if ( (tfDocumentName.text?.hasSuffix(".png"))! == false && (tfDocumentName.text?.hasSuffix(".jpg"))! == false && (tfDocumentName.text?.hasSuffix(".jpeg"))! == false ){
            tfDocumentName.text?.append(".jpg")
        }
        attachment.Name = tfDocumentName.text
        attachment.TableName = "Contacts"
        attachment.TableKey = contactId
        attachment.AttachmentTypeId = documentTypeId
        let imageData: NSData = imageView.image!.jpegData(compressionQuality: 0.8)! as NSData
        let base64Data = imageData.base64EncodedData(options: NSData.Base64EncodingOptions.lineLength64Characters)
        attachment.BinaryData = NSString(data: base64Data, encoding: String.Encoding.utf8.rawValue) as String?
        return attachment
    }
    

    func checkRequiredData(){
        if tfDocumentName.text != nil && tfDocumentName.text != "" && tfDocumentType.text != nil && tfDocumentType.text != "" && imageView.image != nil{
            saveButton.isEnabled = true
        }
        else{
            saveButton.isEnabled = false
        }
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){
        // Local variable inserted by Swift 4.2 migrator.
        let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)

        let chosenImage = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as! UIImage
        imageView.contentMode = .scaleAspectFit
        let maxLength = max(chosenImage.size.height,chosenImage.size.width)
        if maxLength > imageMaxLength{
            let scaleFactor = imageMaxLength / maxLength
            imageView.image = resizeImage(sourceImage: chosenImage, scaledTo: scaleFactor)
        }
        else{
            imageView.image = chosenImage
        }
        checkRequiredData()
        self.dismiss(animated: true, completion: nil)
    }
    
    func resizeImage(sourceImage:UIImage, scaledTo: CGFloat) -> UIImage {
        let newHeight = sourceImage.size.height * scaledTo
        let newWidth = sourceImage.size.width * scaledTo
        
        UIGraphicsBeginImageContext(CGSize(width:newWidth, height:newHeight))
        sourceImage.draw(in: CGRect(x:0, y:0, width:newWidth, height:newHeight))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        checkRequiredData()
        self.dismiss(animated: true, completion: nil)
    }
    
    func delegateTextField(){
        tfDocumentName.delegate = self
        tfDocumentType.delegate = self
    }
    
    
    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none
    }
    
    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField == tfDocumentType{
            self.dismissKeyboard()
            self.openPopUp(tfDocumentType, documentTypes, "DocumentType", "Document type")
            return false
        }
        return true
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == tfDocumentType{
            textField.resignFirstResponder()
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        view.endEditing(true)
        checkRequiredData()
    }
    
    @objc func textFieldDidChange(_ textField: UITextField) {
        if textField == tfDocumentName{
            checkRequiredData()
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        view.endEditing(true)
        return true
    }
    
    func openPopUp(_ textField: UITextField, _ dataSource: [INameable], _ dataSourceType: String, _ title: String ) {
        let popupSelectorViewController = self.storyboard?.instantiateViewController(withIdentifier: "popupSelectorViewController") as! PopupSelectorViewController
        popupSelectorViewController.shouldBeSearchBarHidden = true
        popupSelectorViewController.itemSelectedCallback = selectedValue
        popupSelectorViewController.dataSource = dataSource
        popupSelectorViewController.dataSourceType = dataSourceType
        popupSelectorViewController.title = title
        let nav = UINavigationController(rootViewController: popupSelectorViewController)
        nav.modalPresentationStyle = UIModalPresentationStyle.popover
        let popover = nav.popoverPresentationController
        popover?.permittedArrowDirections = .up
        popupSelectorViewController.preferredContentSize = CGSize(width: textField.frame.size.width, height: 300)
        popover?.delegate = self
        popover?.sourceView = textField
        popover?.sourceRect = CGRect(x: textField.frame.size.width/2.0, y: textField.frame.size.height, width: 0, height: 0)
        self.present(nav, animated: true, completion: nil)
    }
    
    func selectedValue(item: AnyObject, parentItem: AnyObject?){
        let documentType = item as! DocumentType
        tfDocumentType.text = documentType.description
        documentTypeId = documentType.attachmentTypeId
        checkRequiredData()
    }
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] {
	return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)})
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String {
	return input.rawValue
}
