//
//  OTextField.swift
//  NSApplication1.8
//
//  Created by Amine  on 5/9/20.
//  Copyright © 2020 Amine. All rights reserved.
//

import UIKit
import SkyFloatingLabelTextField


class OLongTextField : OField, UITextFieldDelegate, UITextViewDelegate{
    
    override func getField() -> CField? {
        return field
    }
    
    override func getKey() -> String {
        return field!.label
    }
    
    override func getValue() -> String {
        if labelView!.textColor == UIColor.lightGray {
            return ""
        }else{
            return (labelView?.text!)!.trimmingCharacters(in: .whitespacesAndNewlines)
        }
    }
    
    var viewController: UIViewController?
    
    static func newInstance() -> OLongTextField{
        let view = OLongTextField(frame: CGRect(x: 0, y: 0, width: 100, height: 300))
        view.translatesAutoresizingMaskIntoConstraints = false
        
        
        NSLayoutConstraint.activate([
                         view.widthAnchor.constraint(equalToConstant: 100),
                         view.heightAnchor.constraint(equalToConstant: 100),
        ])
        
        return view
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    
    var labelView: UITextView? = nil
    var placeholder: String = "Enter...".localized
    
     var field: CField?

    func setup(field: CField) ->  OLongTextField{
        
        self.field = field
        
        placeholder = field.label
        
        
        if field.required == 1{
            placeholder = field.label+" (*)"
        }else{
            placeholder = field.label
        }
        
        let textField = UITextView(frame: CGRect(x: 0, y: 0, width: .zero, height: .zero))
        textField.delegate = self
        textField.initDefaultFont(size: 16)
        
      
        addSubview(textField)
        addConstraintsWithFormat(format: "H:|[v0]|", views: textField)
        addConstraintsWithFormat(format: "V:|[v0]|", views: textField)
        
        
        textField.inputAccessoryView = setupDoneButtonOnKeyboard()
        self.addLine(position: .LINE_POSITION_BOTTOM, color: UIColor.gray.withAlphaComponent(0.7), width: 0.8)
        
        labelView = textField
        
        textField.text = placeholder
        textField.textColor = UIColor.lightGray
        

        return self
        
    }
    
    
    
    func setupDoneButtonOnKeyboard() -> UIToolbar
    {
        let doneToolbar: UIToolbar = UIToolbar(frame: CGRect(x:0, y:0, width:320, height:50))
        doneToolbar.barStyle = UIBarStyle.default

     let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
     let done: UIBarButtonItem = UIBarButtonItem(title: "Done".localized, style: UIBarButtonItem.Style.done, target: self, action: #selector(doneButtonAction))

        let items = NSMutableArray()
        items.add(flexSpace)
        items.add(done)

        doneToolbar.items = items as? [UIBarButtonItem]
        doneToolbar.sizeToFit()
        
        return doneToolbar
       
    }
    
    @objc func doneButtonAction()
    {
        labelView?.resignFirstResponder()
    }
    
    
    // hides text views
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if (text == "\n") {
            //textView.resignFirstResponder()
            var text = "\(textView.text!)"
            
            if let selectedRange = textView.selectedTextRange {
                let cursorPosition = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
                text.insert("\n", at:  text.index(text.startIndex, offsetBy: cursorPosition))
                textView.text = "\(text)"
            }else{
                textView.text = "\(text)\n"
            }
          
            return false
        }
        return true
    }
    
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.textColor == UIColor.lightGray {
            textView.text = nil
            textView.textColor = UIColor.black
        }
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text.isEmpty {
            textView.text = placeholder
            textView.textColor = UIColor.lightGray
        }
    }
    
}


enum LINE_POSITION {
    case LINE_POSITION_TOP
    case LINE_POSITION_BOTTOM
}

extension UIView {
    func addLine(position : LINE_POSITION, color: UIColor, width: Double) {
        let lineView = UIView()
        lineView.backgroundColor = color
        lineView.translatesAutoresizingMaskIntoConstraints = false // This is important!
        self.addSubview(lineView)

        let metrics = ["width" : NSNumber(value: width)]
        let views = ["lineView" : lineView]
        self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[lineView]|", options:NSLayoutConstraint.FormatOptions(rawValue: 0), metrics:metrics, views:views))

        switch position {
        case .LINE_POSITION_TOP:
            self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[lineView(width)]", options:NSLayoutConstraint.FormatOptions(rawValue: 0), metrics:metrics, views:views))
            break
        case .LINE_POSITION_BOTTOM:
            self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[lineView(width)]|", options:NSLayoutConstraint.FormatOptions(rawValue: 0), metrics:metrics, views:views))
            break
        }
    }
}


