package edu.mingxu.jiaowu;

import android.content.Context;
import android.content.SharedPreferences;

import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;

@CapacitorPlugin(name = "NativeHome")
public class NativeHomePlugin extends Plugin {
    static final String PREFERENCES = "mingxu_native_home";
    static final String WIDGET_PAYLOAD = "widget_payload";
    private static final String PENDING_ROUTE = "pending_route";

    @PluginMethod
    public void updateWidgets(PluginCall call) {
        JSObject payload = call.getObject("payload");
        if (payload == null) {
            call.reject("缺少桌面组件数据。");
            return;
        }

        preferences(getContext()).edit()
            .putString(WIDGET_PAYLOAD, payload.toString())
            .apply();
        WidgetRenderer.updateAll(getContext());
        call.resolve();
    }

    @PluginMethod
    public void clearWidgets(PluginCall call) {
        preferences(getContext()).edit()
            .remove(WIDGET_PAYLOAD)
            .apply();
        WidgetRenderer.updateAll(getContext());
        call.resolve();
    }

    @PluginMethod
    public void getLaunchRoute(PluginCall call) {
        SharedPreferences preferences = preferences(getContext());
        String route = preferences.getString(PENDING_ROUTE, null);
        preferences.edit().remove(PENDING_ROUTE).apply();
        JSObject result = new JSObject();
        if (route != null) {
            result.put("route", route);
        }
        call.resolve(result);
    }

    static void savePendingRoute(Context context, String route) {
        preferences(context).edit().putString(PENDING_ROUTE, route).apply();
    }

    static SharedPreferences preferences(Context context) {
        return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
    }
}
