
import Foundation
import UIKit

//func prepareImageForUpload(_ image: UIImage) throws -> UIImage {
//    return try watermark(image)
//        .flatMap(encrypt)
//        .orThrow(Error.preparationFailed)
//}
extension Optional {
    func orThrow(
        _ errorExpression: @autoclosure () -> Error
        ) throws -> Wrapped {
        guard let value = self else {
            throw errorExpression()
        }
        
        return value
    }
}

//let showInitialTutorial = completedTutorialSteps.isNilOrEmpty
//let hasAddedFriends = !user.friends.isNilOrEmpty
extension Optional where Wrapped: Collection {
    var isNilOrEmpty: Bool {
        return self?.isEmpty ?? true
    }
}

//let activeFriend = database.userRecord(withID: id)
//    .matching { $0.isFriend }
//    .matching { $0.isActive }
//searchBar.text.matching { $0.count > 2 }
//    .map(performSearch)
extension Optional {
    func matching(_ predicate: (Wrapped) -> Bool) -> Wrapped? {
        guard let value = self else {
            return nil
        }
        
        guard predicate(value) else {
            return nil
        }
        
        return value
    }
}

//let statusView = cell.accessoryView.get(orSet: TodoItemStatusView())
//statusView.status = item.status
extension Optional where Wrapped == UIView {
    mutating func get<T: UIView>(
        orSet expression: @autoclosure () -> T
        ) -> T {
        guard let view = self as? T else {
            let newView = expression()
            self = newView
            return newView
        }
        
        return view
    }
}
