//
//  SharingPlugin.swift
//  Astro
//
//  Created by Liz Cross on 2015-11-25.
//  Copyright © 2015 Mobify Research & Development Inc. All rights reserved.
//

import Foundation

public class SharingPlugin: Plugin {

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

        self.addRpcMethodShim("share") { params, respond in
            ////////// This will be autogenerated at some point //////////
            if let options: JSONObject? = MethodShimUtils.getOptionalArg(params, key: "options", respond: respond) {
                self.share(options, respond: respond)
            }
            /////////////////////////////////////////////////////////////
        }
    }

    // @RpcMethod
    func share(_ options: JSONObject?, respond: @escaping RPCMethodCallback) {

        // Note in Facebook app the 'message' doesn't get displayed. Only the
        // url is displayed.
        // Facebook wants developers to use their own sdk for sharing content
        // so they restrict their behaviour when accessing their app
        // via the activityViewController
        let activityItems = createActivityItems(options)

        // Can't be empty
        if activityItems.isEmpty {
            respond(.error("No items exist for sharing."))
            return
        }

        // Initialize the view controller with the message
        let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)

        if let currentViewController = UIApplication.shared.currentViewController {
            // The default modalPresentationStyle results in the eviction of all other views from the view hierarchy
            // when this viewController is presented - which results in degraded webview (app.js) performance. So
            // use OverCurrentContext to maintain modal functionality and retain existing view hierarchy underneath.
            activityViewController.modalPresentationStyle = .overCurrentContext
            currentViewController.present(activityViewController, animated: true, completion: {
                respond(.result(NSNull()))
            })
        } else {
            respond(.error("Can't access root view controller."))
        }
    }

    @objc func createActivityItems(_ options: JSONObject?) -> [Any] {
        var activityItems: [Any] = []

        if let message = messageFromOptions(options) {
            activityItems.append(message)
        }

        if let nsurl = urlFromOptions(options) {
            activityItems.append(nsurl)
        }

        return activityItems
    }

    @objc func urlFromOptions(_ options: JSONObject?) -> URL? {
        if let url = options?["url"] as? String {
            return URL(string: url)
        }
        return nil
    }

    @objc func messageFromOptions(_ options: JSONObject?) -> String? {
        if let message = options?["message"] as? String {
            return message
        }
        return nil
    }
}
