//
//  SklvUtilities
//
//  Copyright (c) 2021-Present Andrew Sokolov (sklv.org)
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//  SOFTWARE.

import Foundation

// Observed

@propertyWrapper
public final class Observed<T: Equatable>: NSObject {
    
    private let queue = DispatchQueue(label: UUID().uuidString, attributes: .concurrent)
    private var value: T
    @objc private(set) dynamic var dynamicValue: Any
    
    // Init
    
    public init(wrappedValue: T) {
        value = wrappedValue
        dynamicValue = wrappedValue
    }
    
    // Wrapped
    
    public var wrappedValue: T {
        get {
            queue.sync() { value }
        }
        set {
            queue.async(flags: .barrier) { [weak self] in
                guard let self = self, newValue != self.value else { return }
                self.value = newValue
                self.dynamicValue = newValue
            }
        }
    }
    
    // Projected
    
    public var projectedValue: Observer<T> {
        Observer(object: self)
    }
    
}

// Observer

public typealias AnyObserver = AnyObject

public final class Observer<T: Equatable> {
    
    private unowned let object: Observed<T>
    private var token: NSKeyValueObservation?
    
    // Init
    
    init(object: Observed<T>) {
        self.object = object
    }
    
    // Change
    
    @discardableResult
    public func change(_ completion: @escaping (T, T) -> Void) -> Observer<T> {
        token?.invalidate()
        
        token = object.observe(\.dynamicValue, options: [.old, .new]) { _, change in
            guard let oldValue = change.oldValue as? T, let newValue = change.newValue as? T else { return }
            completion(oldValue, newValue)
        }
        
        return self
    }
    
    // Store
    
    @discardableResult
    public func store(in array: inout [AnyObserver]) -> Observer<T> {
        array.append(self)
        return self
    }
    
    // Deinit
    
    deinit {
        token?.invalidate()
    }
    
}
