//
//  String+DevHelper.swift
//  DevHelperTests
//
//  Created by Alexey Golovenkov on 05/11/2017.
//  Copyright © 2017 Alexey Golovenkov. All rights reserved.
//

import Foundation

extension String {
    func countInstances(of stringToFind: String, in range: Range<String.Index>) -> Int {
        guard stringToFind.count > 0 else {
            return 0
        }
        var count = 0
        if let foundRange = self.range(of: stringToFind, options: .diacriticInsensitive, range: range) {
            let newRange = (foundRange.upperBound) ..< (range.upperBound)
            count = 1 + countInstances(of: stringToFind, in: newRange)
        }
        return count
    }
    
    func className() -> String? {
        let pattern = "(class|struct|enum) +(?!func\\b)(([A-Z]|_|[0-9])+)"
        guard let regexp = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) else {
            return nil
        }
        
        let string = NSString(string: self)
        let foundStrings = regexp.matches(in: string as String, options: [], range: NSRange(location: 0, length: string.length))
        guard foundStrings.count > 0 else {
            return nil
        }
        let firstResult = foundStrings[0]
        guard firstResult.numberOfRanges > 2 else {
            return nil
        }
        let range = firstResult.range(at: 2)
        let name = string.substring(with: range)
        return name
    }
}
