//
//  KeyboardedViewController.swift
//  kt
//
//  Created by Assylkhan Rakhatov on 04.02.16.
//  Copyright © 2016 Alexandr Zalutskiy. All rights reserved.
//

import Foundation
import UIKit

class KeyboardedViewController : UIViewController, UITextViewDelegate {
    
    let tapGestureRecognizer = UITapGestureRecognizer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tapGestureRecognizer.enabled = false
        tapGestureRecognizer.addTarget(self, action: #selector(KeyboardedViewController.hideKeyboard(_:)))
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        self.view.endEditing(true)
        print("viewWillDisappear")
    }
    
    func hideKeyboard(sender: AnyObject?) {
        view.endEditing(true)
    }
}

// UITextFieldDelegate
extension KeyboardedViewController {
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return false
    }
}

extension UIViewController: UITextFieldDelegate {
    
    public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        
        if (textField.tag == 0) {
            return true
        }
        
        guard let normalText = textField.text else { return false }
        
        let beginning = textField.beginningOfDocument
        
        let cursorLocation = textField.positionFromPosition(beginning, offset: range.location + string.characters.count)
        
        let newString = (normalText as NSString).stringByReplacingCharactersInRange(range, withString: string)
        
        // default mask
        var mask = ""
        var newStringClean = newString
        
        if (textField.tag == 100) {
            mask = "########################"
            newStringClean = newString.withMask(mask)
        } else if (textField.tag == 101) {
            mask = "##########"
            newStringClean = newString.stringWithOnlyNumbers().withMask(mask)
        } else if (textField.tag == 102) {
            mask = "############"
            newStringClean = newString.stringWithOnlyNumbers().withMask(mask)
        }
        
        guard newString != newStringClean else { return true }
        
        textField.text = newStringClean
        guard string != "" else { return false }
        
        // fix cursor location after changing textfield.text
        if let cL = cursorLocation {
            let textRange = textField.textRangeFromPosition(cL, toPosition: cL)
            textField.selectedTextRange = textRange
        }
        
        return false
    }
}

extension String {
    
    func stringWithOnlyNumbers() -> String {
        return self.characters.reduce("") { (acc, c) -> String in
            guard c.isDigit() else { return acc }
            return "\(acc)\(c)"
        }
    }
    
    func withMask(mask: String) -> String {
        var resultString = String()
        let chars = self.characters
        let maskChars = mask.characters
        var stringIndex = chars.startIndex
        var maskIndex = mask.startIndex
        while stringIndex < chars.endIndex && maskIndex < maskChars.endIndex {
            if (maskChars[maskIndex] == "#") {
                resultString.append(chars[stringIndex])
                stringIndex = stringIndex.successor()
            } else {
                resultString.append(maskChars[maskIndex])
            }
            maskIndex = maskIndex.successor()
        }
        return resultString
    }
}

extension Character {
    func isDigit() -> Bool {
        let s = String(self).unicodeScalars
        let uni = s[s.startIndex]
        let digits = NSCharacterSet.decimalDigitCharacterSet()
        let isADigit = digits.longCharacterIsMember(uni.value)
        return isADigit
    }
}
