/*
 * Copyright (C) 2025 The Android Open Source Project
 *
 * 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 android.security.talisman;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.os.Parcel;
import android.os.Parcelable;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
import java.util.Objects;

/**
 * A set of talismans that share a public key.
 *
 * <p>A talisman identity set contains a "verified device" talisman and a collection of
 * identity-bound talismans. All talismans in the set are guaranteed to have the same public key.
 * This allows a device to present the verified device talisman to a peer, and then later provide
 * an identity talisman to prove an identity once more trust has been established.
 *
 * @see {@link TalismanManager#getTalismanIdentitySet(String...)}
 * @hide
 */
public final class TalismanIdentitySet implements Parcelable {

    private final Talisman mVerifiedDeviceTalisman;
    private final Map<String, Talisman> mIdentityTalismans;
    private final byte[] mSecretKey;

    /**
     * Creates a new talisman identity set.
     *
     * @param verifiedDeviceTalisman the "verified device" talisman.
     * @param identityTalismans a map of identity strings to their corresponding talismans.
     * @param secretKey the secret key for identity-related cryptographic operations.
     */
    public TalismanIdentitySet(@NonNull Talisman verifiedDeviceTalisman,
            @NonNull Map<String, Talisman> identityTalismans,
            @NonNull byte[] secretKey) {
        mVerifiedDeviceTalisman = Objects.requireNonNull(verifiedDeviceTalisman);
        mIdentityTalismans = new HashMap<>(Objects.requireNonNull(identityTalismans));
        mSecretKey = Objects.requireNonNull(secretKey).clone();

        // TODO(b/418280383): Verify that all talismans have the same public key.
    }

    private TalismanIdentitySet(Parcel in) {
        mVerifiedDeviceTalisman = in.readTypedObject(Talisman.CREATOR);
        int size = in.readInt();
        mIdentityTalismans = new HashMap<>(size);
        for (int i = 0; i < size; i++) {
            String key = in.readString();
            Talisman value = in.readTypedObject(Talisman.CREATOR);
            mIdentityTalismans.put(key, value);
        }
        mSecretKey = in.createByteArray();
    }

    /**
     * Returns the "verified device" talisman.
     */
    @NonNull
    public Talisman getVerifiedDeviceTalisman() {
        return mVerifiedDeviceTalisman;
    }

    /**
     * Returns the identity talisman for the given identity.
     *
     * @param identity the identity to look up.
     * @return the talisman, or null if no talisman is present for the given identity.
     */
    @Nullable
    public Talisman getIdentityTalisman(@NonNull String identity) {
        return mIdentityTalismans.get(identity);
    }

    /**
     * Returns the secret key used to generate the {@code
     * encrypted_identity_hash} in the identity talismans.
     *
     * TODO: Figure the right way to represent the key in this API. We either need to set a stable
     * encryption algorithm (and therefore key type) in Talisman & Transformer, or we need to expose
     * the algorithm in the identity talisman along with the encrypted identity hash.
     *
     * @return a copy of the secret key.
     */
    @NonNull
    public byte[] getSecretKey() {
        return mSecretKey.clone();
    }


    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(@NonNull Parcel dest, int flags) {
        dest.writeTypedObject(mVerifiedDeviceTalisman, flags);
        dest.writeInt(mIdentityTalismans.size());
        for (Map.Entry<String, Talisman> entry : mIdentityTalismans.entrySet()) {
            dest.writeString(entry.getKey());
            dest.writeTypedObject(entry.getValue(), flags);
        }
        dest.writeByteArray(mSecretKey);
    }

    @NonNull
    public static final Creator<TalismanIdentitySet> CREATOR =
            new Creator<TalismanIdentitySet>() {
                @Override
                public TalismanIdentitySet createFromParcel(Parcel in) {
                    return new TalismanIdentitySet(in);
                }

                @Override
                public TalismanIdentitySet[] newArray(int size) {
                    return new TalismanIdentitySet[size];
                }
            };

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof TalismanIdentitySet)) return false;
        TalismanIdentitySet that = (TalismanIdentitySet) o;
        return mVerifiedDeviceTalisman.equals(that.mVerifiedDeviceTalisman)
                && mIdentityTalismans.equals(that.mIdentityTalismans)
                && Arrays.equals(mSecretKey, that.mSecretKey);
    }

    @Override
    public int hashCode() {
        int result = Objects.hash(mVerifiedDeviceTalisman, mIdentityTalismans);
        return 31 * result + Arrays.hashCode(mSecretKey);
    }
}
