package org.wikimedia.wikipedia;

import android.content.Context;
import android.util.Log;
import com.squareup.otto.Bus;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Handles any html links coming from a {@link PageViewFragment}
 */
public class LinkHandler implements CommunicationBridge.JSEventListener {
    private final Context context;
    private final CommunicationBridge bridge;
    private final Bus bus;

    public static class NewWikiPageNavigationEvent {
        private final PageTitle title;

        public NewWikiPageNavigationEvent(PageTitle title) {
            this.title = title;
        }

        public PageTitle getTitle() {
            return title;
        }
    }

    public LinkHandler(Context context, CommunicationBridge bridge) {
        this.context = context;
        this.bridge = bridge;
        this.bus = ((WikipediaApp)context.getApplicationContext()).getBus();

        this.bridge.addListener("linkClicked", this);
    }

    @Override
    public void onMessage(String messageType, JSONObject messagePayload) {
        try {
            String href = messagePayload.getString("href");
            if (href.startsWith("/wiki/")) {
                // TODO: Handle fragments
                String pageName = href.replace("/wiki/", "");
                bus.post(new NewWikiPageNavigationEvent(new PageTitle(null, pageName)));
            }
            Log.d("Wikipedia", "Link clicked was " + href);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
}

@@ -59,16 +59,71 @@
 ontext;%0A
+import android.content.Intent;%0Aimport android.net.Uri;%0A
 import a
@@ -1042,164 +1042,608 @@
     
-@Override%0A    public void onMessage(String messageType, JSONObject messagePayload) %7B%0A        try %7B%0A            String href = messagePayload.getString(%22href%22
+private void handleExternalLink(String href) %7B%0A        Intent intent = new Intent();%0A        intent.setAction(Intent.ACTION_VIEW);%0A        intent.setData(Uri.parse(href));%0A        context.startActivity(intent);%0A    %7D%0A%0A    @Override%0A    public void onMessage(String messageType, JSONObject messagePayload) %7B%0A        try %7B%0A            String href = messagePayload.getString(%22href%22);%0A            if (href.startsWith(%22//%22)) %7B%0A                // That's a protocol specific link! Make it https!%0A                href = %22https:%22 + href;%0A            %7D%0A            Log.d(%22Wikipedia%22, %22Link clicked was %22 + href
 );%0A 
@@ -1884,32 +1884,39 @@
 );%0A            %7D
+ else %7B
 %0A            Log
@@ -1916,55 +1916,125 @@
     
-Log.d(%22Wikipedia%22, %22Link clicked was %22 + href);
+    // Assume everything else is an external link... for now!%0A                handleExternalLink(href);%0A            %7D
 %0A   

Handle external links