//
//  ComponentEvent.swift
//  
//  Copyright © 2016-2019 Apple Inc. All rights reserved.
//

import Foundation
import PlaygroundSupport
import SPCCore

typealias ComponentEventName = String

public struct ComponentEvent: Codable {
    var name: ComponentEventName
    var value: PlaygroundValue
}

public extension ComponentEvent {
    
    func sendLocally(to component: Component, in environment: Environment) {
        let message = ComponentMessage.event(origin: ComponentMessageOrigin.current, identity: component.identity, event: self)
        
        switch environment {
        case .live:
            guard let proxy = PlaygroundPage.current.liveView as? PlaygroundRemoteLiveViewProxy else { return }
            //PBLog("\(self.name) to: \(component.name) in LVP")
            proxy.send(message.playgroundValue)
            
        case .user:
            guard let liveViewMessageHandler = PlaygroundPage.current.liveView as? PlaygroundLiveViewMessageHandler else { return }
            //PBLog("\(self.name) to: \(component.name) in UP")
            liveViewMessageHandler.send(message.playgroundValue)
        }
    }
    
    func sendRemotely(to component: Component, in environment: Environment) {

    }

    func send(to component: Component, in environment: Environment) {
        sendLocally(to: component, in: environment)
        sendRemotely(to: component, in: environment)
    }
    
}
