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

import Foundation
import PlaygroundSupport
import SPCCore
import SPCComponents

/// An enumeration of messages that can be sent between the User and Live View environments.
public enum CameraFunMessage: PlaygroundMessage {
    case showGrid(origin: ComponentMessageOrigin)
    
    public enum MessageType: String, PlaygroundMessageType {
        case showGrid
    }
    
    public var messageType: MessageType {
        switch self {
        case .showGrid(origin:):
            return .showGrid
        }
    }
    
    public init?(messageType: MessageType, encodedPayload: Data?) {
        let decoder = JSONDecoder()
        
        switch messageType {
        case .showGrid:
            guard let payload = encodedPayload,
                let object = try? decoder.decode(ComponentMessageOrigin.self, from: payload) else { return nil }
            self = .showGrid(origin: object)
        }
    }
    
    public func encodePayload() -> Data? {
        let encoder = JSONEncoder()
        
        switch self {
        case let .showGrid(origin: origin):
            let payload = origin
            return try! encoder.encode(payload)

        }
    }
}

public extension CameraFunMessage {
    
    func send(to destination: Environment = .live) {
        switch destination {
        case .live:
            guard let proxy = PlaygroundPage.current.liveView as? PlaygroundRemoteLiveViewProxy else { return }
            proxy.send(self.playgroundValue)
        case .user:
            guard let liveViewMessageHandler = PlaygroundPage.current.liveView as? PlaygroundLiveViewMessageHandler else { return }
            liveViewMessageHandler.send(self.playgroundValue)
        }
    }
}
