# NubrickSDK

`NubrickSDK` は Android SDK のエントリポイントです。初期化、イベント送信、埋め込み、Remote Config、ユーザープロパティ更新を扱います。

{% hint style="warning" %}
`NubrickSDK.initialize(...)` は、アプリ起動時に 1 回だけ実行してください。\
推奨: `Application` の `onCreate` で初期化してください。\
`Embedding` / `RemoteConfig` / `dispatch` などの API は、初期化完了後に利用してください。\
Compose でオーバーレイ配信を表示する場合は、`NubrickProvider { ... }` でルートを包んでください。
{% endhint %}

### 定義

```kotlin
object NubrickSDK {
    fun initialize(
        context: Context,
        config: Config
    )

    fun dispatch(event: NubrickEvent)

    fun setUserId(id: String)
    fun getUserId(): String?

    fun setUserProperty(key: String, value: Any)
    fun getUserProperty(key: String): String?

    fun setUserProperties(props: Map<String, Any>)
    fun getUserProperties(): Map<String, String>

    @Composable
    fun Embedding(
        id: String,
        modifier: Modifier = Modifier,
        arguments: Any? = null,
        onEvent: ((event: Event) -> Unit)? = null,
        content: (@Composable (state: EmbeddingLoadingState) -> Unit)? = null,
        onSizeChange: ((width: NubrickSize, height: NubrickSize) -> Unit)? = null
    )

    @Composable
    fun RemoteConfig(
        id: String,
        content: @Composable (RemoteConfigLoadingState) -> Unit
    )

    fun remoteConfig(id: String): Result<app.nubrick.nubrick.remoteconfig.RemoteConfig>
}

data class Config(
    val projectId: String,
    val onEvent: ((event: Event) -> Unit)? = null,
    val onDispatch: ((event: NubrickEvent) -> Unit)? = null,
    val trackCrashes: Boolean = true,
)

sealed class NubrickSize {
    data class Fixed(val value: Int) : NubrickSize()
    data object Fill : NubrickSize()
}
```

### 初期化

```kotlin
import android.app.Application
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import app.nubrick.nubrick.Config
import app.nubrick.nubrick.NubrickProvider
import app.nubrick.nubrick.NubrickSDK

class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        NubrickSDK.initialize(
            context = this,
            config = Config(projectId = "<YOUR_PROJECT_ID>")
        )
    }
}

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            NubrickProvider {
                AppContent()
            }
        }
    }
}
```

### イベント送信

カスタムイベントを発火させる

```kotlin
import app.nubrick.nubrick.NubrickEvent
import app.nubrick.nubrick.NubrickSDK

NubrickSDK.dispatch(NubrickEvent("PURCHASE_COMPLETED"))
```

### 埋め込み（Compose）

```kotlin
NubrickSDK.Embedding("TOP_COMPONENT")
```

フェーズを使う場合:

```kotlin
import app.nubrick.nubrick.component.EmbeddingLoadingState

NubrickSDK.Embedding("TOP_COMPONENT") { state ->
    when (state) {
        is EmbeddingLoadingState.Loading -> CircularProgressIndicator()
        is EmbeddingLoadingState.Completed -> state.view()
        is EmbeddingLoadingState.NotFound -> Text("not found")
        is EmbeddingLoadingState.Failed -> Text("error")
    }
}
```

### 埋め込みサイズの取得

`onSizeChange` を使うと、埋め込みコンポーネントの実サイズを取得できます。\
このコールバックは、実際の埋め込みページが読み込まれたときだけ呼ばれます。`Loading` / `NotFound` / `Failed` では呼ばれません。

```kotlin
NubrickSDK.Embedding(
    id = "TOP_COMPONENT",
    onSizeChange = { width, height ->
        println("width=$width, height=$height")
    }
)
```

`NubrickSize` の意味:

* `NubrickSize.Fixed(value)` は、エディタで固定サイズが設定されていることを表します。
* `NubrickSize.Fill` は、その軸に固定サイズがなく、ホスト側のレイアウトに従うことを表します。

### Remote Config

```kotlin
import app.nubrick.nubrick.remoteconfig.RemoteConfigLoadingState

NubrickSDK.RemoteConfig("FEATURE_FLAGS") { state ->
    when (state) {
        is RemoteConfigLoadingState.Completed -> {
            val enabled = state.variant.getAsBoolean("new_checkout") ?: false
            Text("enabled=$enabled")
        }
        is RemoteConfigLoadingState.Loading -> CircularProgressIndicator()
        is RemoteConfigLoadingState.NotFound -> Text("not found")
        is RemoteConfigLoadingState.Failed -> Text("error")
    }
}
```

### ユーザープロパティ

{% hint style="warning" %}
この値は、エクスペリメントのデータを識別するためにNubrickサーバーに送信されます。そのため、氏名やメールアドレスなどの個人情報は、user\_id として使用しないでください。\
詳細はこちらのドキュメントもご覧ください。

[ユーザー属性情報（setProperties）について](/other/setproperties.md)
{% endhint %}

{% hint style="info" %}
このプロパティは、

* どのユーザーがエクスペリメントのターゲットとなるかをフィルタリングする
* エクスペリメント内のユーザー毎の動的な変数として表示する

ために使用されます。
{% endhint %}

```kotlin
NubrickSDK.setUserProperties(
    mapOf(
        "plan" to "gold",
        "isPremium" to true,
        "age" to 32
    )
)

NubrickSDK.setUserId("<CUSTOM_USER_ID>")

val userId = NubrickSDK.getUserId()
val props = NubrickSDK.getUserProperties()
```

### ビルトインのユーザープロパティ

デフォルトで、以下のビルトインプロパティが設定されています：

| Key            | Description                                           |
| -------------- | ----------------------------------------------------- |
| `userId`       | User id (uuid by default)                             |
| `languageCode` | language code (e.g. ja for Japanese, en for English)  |
| `regionCode`   | region code (e.g. JP for Japan, US for United States) |
| `sdkVersion`   | nubrick sdk version                                   |
| `osName`       | os name (Android)                                     |
| `osVersion`    | Android API level                                     |
| `appId`        | your app package name                                 |
| `appVersion`   | your app version                                      |

### 補足

* `setUserProperties` / `setUserProperty` の値は `String`, `Boolean`, `Int`, `Double` などを渡せます。
* `getUserProperties()` は、アプリが設定したカスタム値と `userId` を取得できます。
* 失敗系の状態は [Phases](/reference/android/phases.md) を参照してください。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.nubrick.app/reference/android/nubricksdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
