/*
 * Copyright 2025 Circle Internet Group, Inc. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cybavo.reactnative.wallet.service;

import android.util.Log;
import android.util.SparseArray;

import com.cybavo.wallet.service.auth.PinSecret;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableType;

public class PinSecretBridge {

    private static final String TAG = "PinSecretBridge";
    private static SparseArray<PinSecret> sPinSecrets = new SparseArray<>();

    private static PinSecret get(int key) {
        PinSecret pinSecret = sPinSecrets.get(key);
        if (pinSecret == null) {
            Log.e(TAG, "PinSecret not found: " + key);
            return null;
        }
        return pinSecret;
    }

    private static void delete(int key) {
        sPinSecrets.delete(key);
    }

    public static int put(PinSecret pinSecret) {
        final int key = pinSecret.hashCode();
        sPinSecrets.put(key, pinSecret);
        return key;
    }

    private final static String PIN_SECRET_KEY = "pinSecret";
    private final static String RETAIN = "retain";
    public static PinSecret fromReadableMap(ReadableMap readableMap) {
        if (readableMap == null) {
            Log.e(TAG, "Null readableMap");
            return null;
        }
        if (!readableMap.hasKey(PIN_SECRET_KEY) || readableMap.getType(PIN_SECRET_KEY) != ReadableType.Number) {
            Log.e(TAG, "Invalid key");
            return null;
        }
        final int key = readableMap.getInt(PIN_SECRET_KEY);
        final PinSecret pinSecret = get(key);
        if (pinSecret == null) {
            Log.e(TAG, "Key Not found");
            return null;
        }
        if (readableMap.hasKey(RETAIN) && readableMap.getType(RETAIN) == ReadableType.Boolean && readableMap.getBoolean(RETAIN)) {
            pinSecret.retain();
        } else {
            delete(key);
        }
        return pinSecret;
    }
}
