package com.mobify.astro.plugins;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.util.Log;

import com.mobify.astro.AstroActivity;
import com.mobify.astro.AstroPlugin;
import com.mobify.astro.PluginResolver;
import com.mobify.astro.R;
import com.mobify.astro.messaging.EventRegistrar;
import com.mobify.astro.messaging.MessageSender;
import com.mobify.astro.messaging.annotations.RpcMethod;
import com.mobify.astro.utilities.StringUtilities;

import org.json.JSONException;
import org.json.JSONObject;

public class SharingPlugin extends AstroPlugin {
    private static final String TAG = SharingPlugin.class.getName();
    final protected static String messageKey = "message";
    final protected static String urlKey = "url";

    public SharingPlugin(@NonNull AstroActivity activity, @NonNull PluginResolver pluginResolver,
                         @NonNull EventRegistrar eventRegistrar, @NonNull MessageSender messageSender) {
        super(activity, pluginResolver, eventRegistrar, messageSender);
    }

    @RpcMethod(methodName = "share", parameterNames = {"options"})
    public void share(JSONObject options) {
        String sharingText = StringUtilities.joinWithSpaces(
                retrieveOption(options, messageKey),
                retrieveOption(options, urlKey));

        // No input received so no need to share anything
        if (sharingText.isEmpty()) {
            Log.e(TAG, "Message and url were both empty.");
            return;
        }

        Intent sendIntent = createSharingIntent(sharingText);
        activity.startActivity(Intent.createChooser(sendIntent, getChooserTitle()));
    }

    protected CharSequence getChooserTitle() {
        return activity.getResources().getText(R.string.sharing_label);
    }

    protected static Intent createSharingIntent(String sharingText) {
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);

        // 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 handling intents
        sendIntent.putExtra(Intent.EXTRA_TEXT, sharingText);
        sendIntent.setType("text/plain");
        return sendIntent;
    }

    protected static String retrieveOption(JSONObject options, String key) {
        String value = "";

        try {
            if (options.has(key)) {
                value = options.getString(key);
            }
        } catch (JSONException e) {
            Log.d(TAG, e.getMessage());
        }
        return value;
    }
}
