//
//  ImageViewPlugin.swift
//  Astro
//
//  Created by Liz Cross on 2015-05-28.
//  Copyright (c) 2015 Mobify Research & Development Inc. All rights reserved.
//

import Foundation

open class ImageViewPlugin: Plugin, ViewPlugin {
    @objc public let viewController = UIViewController()

    private let imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.contentMode = .center
        return imageView
    }()

    public required init(address: MessageAddress, messageBus: MessageBus, pluginResolver: PluginResolver, options: JSONObject?) {
        super.init(address: address, messageBus: messageBus, pluginResolver: pluginResolver, options: options)

        self.addAsyncRpcMethodShim("setImagePath") { params, respond in
            ////////// This will be autogenerated at some point //////////
            if let path: String = MethodShimUtils.getArg(params, key: "path", respond: respond) {
                self.setImagePath(path, respond: respond)
            }
            /////////////////////////////////////////////////////////////
        }

        viewController.view.addSubview(imageView)
        imageView.pinToSuperviewEdges()
    }

    // @RpcMethod
    func setImagePath(_ path: String, respond: @escaping RPCMethodCallback) {
        AstroFileUtils.image(path: path, respond: respond, success: {(image: UIImage) in
            self.imageView.image = image
            respond(.result(NSNull()))
        })
    }
}
