// depends on https://github.com/coryalder/LevenshteinSwift

class SuggestionController {
  // has a couple of notable vars:
  // delegate, where the inputted text is loaded from
  // rawCompletions, an array of possible suggestions (unfiltered)
  // autocompletions, the filtered array of suggestions we're offer up to the user

  func filterAutocompletions() {
        
        let campaignField = delegate!.campaignField
        let _ = delegate?.longUrl
        
        guard let string = campaignField.text where string.characters.count > 0 else {
            self.autocompletions = self.rawCompletions
            suggestionTable.reloadData()
            return
        }
        
        var mapped = rawCompletions.map {
            ($0.limit(string.characters.count).asciiLevenshteinDistance(string), $0)
        }
        
        mapped.sortInPlace {
            $0.0 < $1.0
        }
        
        let resultsCount = max(mapped.count - 1, 0)
        let lim = min(resultsCount, 10)
        
        // protect against 0...lim when lim == 0
        let slice: Array<(Int, String)> = {
            if lim > 0 {
                return Array(mapped[0...lim])
            } else {
                return mapped
            }
            }()
        
        let out = slice.map {
            $0.1
        }
        
        self.autocompletions = out
        
        suggestionTable.reloadData()
    }
}

// limit strings to a specific length. "twitter".limit(2) == "tw"
public extension String {
    func limit(n: Int) -> String {
        let actual = min(self.characters.count, n)
        let ind = startIndex.advancedBy(actual)
        return substringToIndex(ind)
    }
}