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

import Foundation

func containsLetters(checkString: String) -> Bool {
  let characterSet:NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ")
  let nsStringed = NSString(string: checkString)
  if (nsStringed.rangeOfCharacterFromSet(characterSet.invertedSet).location == NSNotFound){
    return true
  }
  return false
}

func containsCharacter(checkString: String, containingCharacters: String) -> Bool {
  let characterSet:NSCharacterSet = NSCharacterSet(charactersInString: containingCharacters)
  let nsStringed = NSString(string: checkString)
  if (nsStringed.rangeOfCharacterFromSet(characterSet.invertedSet).location != NSNotFound){
    return true
  }
  return false
}

// formats numbers into phone number with +7 prefix
func getFormattedPhone(phone: String) -> String {
    //print("phone: \(phone)")
    
    let decimalString = getDigitsFromString(phone)
    //print ("decimalString: \(decimalString)")
    
    let length = decimalString.length
    
    let hasLeadingSeven = length > 0 && phone.hasPrefix("+7")
    
    var index = 0 as Int
    let formattedString = NSMutableString()
    
    
    formattedString.appendString("+7 ")
    
    if hasLeadingSeven {
        index += 1
    }
    
    if (length - index) > 3 {
        let areaCode = decimalString.substringWithRange(NSMakeRange(index, 3))
        formattedString.appendFormat("%@ ", areaCode)
        index += 3
    }
    
    if length - index > 3 {
        let prefix = decimalString.substringWithRange(NSMakeRange(index, 3))
        formattedString.appendFormat("%@-", prefix)
        index += 3
    }
    
    let remainder = decimalString.substringFromIndex(index)
    
    let first4 = String(remainder.characters.prefix(4))
    
    formattedString.appendString(first4)
    return formattedString as String
}

// returns digits from any string
func getDigitsFromString(str : String ) -> NSString {
    let components = str.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
    let decimalString = components.joinWithSeparator("") as NSString
    return decimalString
}

// returns 7019995500
func getPhoneDigits(phone : String) -> String {
    let decimalString = getDigitsFromString(phone)
    
    if ( phone.hasPrefix("+7") ) {
        return String(decimalString.substringFromIndex(1))
    } else {
        return String(decimalString.substringFromIndex(0))
    }
}
