package com.mobify.astro;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

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

public class DeepLinkHandler {
    private static final String TAG = DeepLinkHandler.class.getName();
    public static final String PUSH_NOTIFICATION_CLICKED_BROADCAST_ID = "pushNotificationClickedBroadcastId";

    // The AstroActivity can get restarted with the same deeplink intent multiple times
    // DeepLinkHandler and the savedInstanceState in the AstroActivity track whether or not
    // the deep link associated with an intent has yet to be handled
    protected boolean consumedIntent;
    protected boolean appStartedWithDeepLink;

    private Context context;
    private AstroApplication application;
    private String startUri;
    protected Bundle pushNotificationsExtraFromStartup;

    public DeepLinkHandler(Context context, AstroApplication application) {
        this.context = context;
        this.application = application;

        consumedIntent = false;
        appStartedWithDeepLink = false;
        startUri = null;
        pushNotificationsExtraFromStartup = null;
    }

    public void setConsumedIntent(boolean consumedIntent) {
        this.consumedIntent = consumedIntent;
    }

    public boolean getConsumedIntent() {
        return consumedIntent;
    }

    public void setAppStartedWithDeepLink(boolean appStartedWithDeepLink) {
        this.appStartedWithDeepLink = appStartedWithDeepLink;
    }

    public String getStartUri() {
        return startUri;
    }

    public void attemptDeepLinkHandling(Intent intent) {
        boolean launchedFromHistory = intent != null ? (intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0 : false;

        Log.d(TAG, "Intent: " + intent + " Consumed Intent?: " + consumedIntent + " Launched from history: " + launchedFromHistory);
        if(!launchedFromHistory && !consumedIntent) {
            consumedIntent = true;
            //execute the code that should be executed if the activity was not launched from history
            handleDeepLink(intent);
        }
    }

    private void handleDeepLink(Intent intent) {
        // Supporting opening deep link from sources other than push notifications
        String uri = intent.getDataString();
        if (uri != null) {
            // When passing a link via a custom URI scheme deeplink, iOS will not
            // preserve the ':' in the link, but using 'appscheme:///' fixes this
            // Strip any leading 'appscheme:///' on Android to keep in sync
            // with this behaviour (see AstroViewController.swift for more)
            uri = uri.replaceFirst(intent.getScheme() + ":///", "");
            directDeepLink(uri);
        }
    }

    private void directDeepLink(String uri) {
        if (appStartedWithDeepLink) {
            startUri = uri;
        } else {
            startUri = null;
            triggerDeepLinkEvent(uri);
        }
    }

    private void triggerDeepLinkEvent(String uri) {
        JSONObject data = new JSONObject();
        try {
            data.put("uri", uri);
            application.deepLink(data);
        } catch (JSONException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }
    }
}
