//
//  String+Extensions.swift
//  xray
//
//  Created by Anton Kononenko on 7/10/20.
//  Copyright © 2020 Applicaster. All rights reserved.
//

import Foundation

extension String {
    func deletingPrefix(_ prefix: String) -> String {
        guard hasPrefix(prefix) else {
            return self
        }
        return String(dropFirst(prefix.count))
    }

    func retrieveParentSubsystemPath() -> String? {
        guard let lastSeparatorIndex = lastIndex(of: "/") else {
            return nil
        }

        let parentSubsystem = String(self[..<lastSeparatorIndex])
        return parentSubsystem
    }

    public var currentChildSubsystem: String {
        guard let lastSeparatorIndex = lastIndex(of: "/") else {
            return self
        }

        let currentChildSubsystem = String(self[index(after: lastSeparatorIndex)...])
        return currentChildSubsystem
    }

    /// The subsystem without a leading app bundle id. Only a first segment that is the bundle id of the running
    /// app is removed: subsystems no longer carry one (`player/...`, `plugins/...`), and dropping their
    /// first segment would cut the domain off.
    public var subsystemWithoutAppBundlePrefix: String {
        guard let bundleIdentifier = Bundle.main.bundleIdentifier,
              hasPrefix(bundleIdentifier + "/") else {
            return self
        }
        return String(dropFirst(bundleIdentifier.count + 1))
    }

//    func isSubsystemPathCorrupeted() -> Bool {
//        let regexLiteral = "^(?:[.\\/\\\\ ](?![.\\/\\\\\\n])|[^<>:\"|?*.\\/\\\\ \\n])+$"
//
//        let regex = try! NSRegularExpression(pattern: regexLiteral,
//                                             options: NSRegularExpression.Options.caseInsensitive)
//        let range = NSMakeRange(0, count)
//
//        return regex.numberOfCaptureGroups > 0
//    }
//
//    func removeDuplicationDelimiterOfSubsystemPath() -> String {
//        let regexLiteral = "(\\/)\\1+"
//        let regex = try! NSRegularExpression(pattern: regexLiteral,
//                                             options: NSRegularExpression.Options.caseInsensitive)
//        let range = NSMakeRange(0, count)
//        let retVal = regex.stringByReplacingMatches(in: self,
//                                                    options: [],
//                                                    range: range,
//                                                    withTemplate: "/")
//        return retVal
//    }
}
