package com.mobify.astro.plugins.headerbarplugin;

import android.app.Activity;
import android.util.Log;

import com.mobify.astro.PluginResolver;

import org.json.JSONObject;

public class HeaderContent {
    private static final String TAG = HeaderContent.class.getName();

    static final String LEFT_ICON_KEY = "leftIcon";
    static final String CENTER_ICON_KEY = "centerIcon";
    static final String RIGHT_ICON_KEY = "rightIcon";

    public HeaderContentItem leftIcon;
    public HeaderContentItem centerIcon;
    public HeaderContentItem rightIcon;

    public static HeaderContent fromJson(PluginResolver pluginResolver, Activity activity, JSONObject jsonObject) {
        if (jsonObject == null) {
            return null;
        }

        HeaderContent headerContent = new HeaderContent();
        headerContent.leftIcon = tryGetJSONObject(pluginResolver, activity, jsonObject, LEFT_ICON_KEY);
        headerContent.centerIcon = tryGetJSONObject(pluginResolver, activity, jsonObject, CENTER_ICON_KEY);
        headerContent.rightIcon = tryGetJSONObject(pluginResolver, activity, jsonObject, RIGHT_ICON_KEY);

        return headerContent;
    }

    private static HeaderContentItem tryGetJSONObject(PluginResolver pluginResolver, Activity activity, JSONObject jsonObject, String key) {
        if (jsonObject.has(key)) {
            try {
                return HeaderContentItem.fromJson(
                        pluginResolver, activity, jsonObject.getJSONObject(key)
                );
            } catch (Exception e) {
                Log.e(TAG, String.format("Could not find '%s' in JSON object: %s", key, jsonObject), e);
            }
        }

        return null;
    }
}
