# Reference

## Flagship

The `Flagship` class represents the SDK. It facilitates the initialization process and creation of new visitors.

### `start`

Initialize and start the flagship SDK, using your credential with a custom configuration implementation.

**Signature**

`suspend fun start(application: Application, envId: String, apiKey: String, config: FlagshipConfig<*>)`

**Parameters**

| Parameter   | Type               | Description                                                                               |
| ----------- | ------------------ | ----------------------------------------------------------------------------------------- |
| application | Application        | your Android application base class.                                                      |
| envId       | String             | Environment id provided by Flagship.                                                      |
| apiKey      | String             | Api authentication key provided by Flagship.                                              |
| config      | FlagshipConfig<\*> | Flagship configuration to use. [See Configuration](docs:android-reference#configuration). |

{% hint style="info" %}
📘 Environment ID and API Key

You can find your **Environment Id** and your **API Key** on your Flagship account, in Parameters > Environment & Security.\\
{% endhint %}

**Example**

```kotlin
class MyActivity : Activity() {
  
    override fun onCreate(savedInstanceState: Bundle?) {
      
        super.onCreate(savedInstanceState)
        
        Flagship.start(getApplication(),"_ENV_ID_", "_API_KEY_", FlagshipConfig.DecisionApi()
    }
}
```

### `newVisitor`

Return a Visitor Builder class that wiill help to create a new visitor instance.

**Signature**

`fun newVisitor(visitorId: String, consent: Boolean, instanceType: Visitor.Instance = Visitor.Instance.SINGLE_INSTANCE): Visitor.Builder`

**Parameters**

| Parameter    | Type             | Description                                                                                                                                                                           |
| ------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorId    | String           | Unique visitor identifier.                                                                                                                                                            |
| consent      | Boolean          | Specify if the visitor has consented for personal data usage. When false some features will be deactivated, Pending hits and cache will be deactivated and cleared.                   |
| instanceType | Visitor.Instance | How Flagship SDK should handle the newly created visitor instance. (Default is SINGLE\_INSTANCE). See [Visitor.Instance](doc:android-reference#visitorinstance) for more information. |

**Example**

```kotlin
 val visitor = Flagship.newVisitor("visitor_uuid", true)
                .context(hashMapOf("isVIP" to true))
                .build()
```

### `getConfig`

Return the current used configuration.

**Signature**

`fun getConfig(): FlagshipConfig<*>`

**Example**

```kotlin
val currentConfiguration = Flagship.getConfig()
```

### `getVisitor`

This method will return any previous created visitor instance initialized with the SINGLE\_INSTANCE (Set by default) option.

**Signature**

`fun getVisitor() : Visitor?`

**Example**

```kotlin
 val visitor = Flagship.getVisitor()
```

### `getStatus`

Return the current SDK status. See [Flagship.Status](#status) for more information.

**Signature**

`fun getStatus(): Status`

**Example**

```kotlin
 val flagshipStatus = Flagship.getStatus()
```

### `stop`

Stop the Flagship SDK. Any data and background job will be cleared or stopped.

**Signature**

`suspend fun stop()`

**Example**

```kotlin
Flagship.stop()
```

## Flagship.DecisionMode

This enum class used by the implementation of FlagshipConfig will makes the Flagship SDK run in two different modes.

**Values**

| DecisionMode  | Description                                                                                                                                                                                                                                                                                                                                                                                                         |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| DECISION\_API | (default) When the SDK is running in `DECISION_API` mode, the campaign assignments and targeting validation take place server-side. In this mode, each call to the `fetchFlags` method to refresh the flags will create an HTTP request.                                                                                                                                                                            |
| BUCKETING     | When the SDK is running in `BUCKETING` mode, the SDK downloads all the campaigns configurations at once in a single bucketing file so that variation assignment and targeting validation can be computed client-side by the SDK. This bucketing file is stored in cache and will only be downloaded again when campaign configurations are modified in the Flagship interface. \*\*[Learn more](doc:bucketing) \*\* |

## Flagship.FlagshipStatus

This enum class defines the current SDK Status. All possible status are:

**Values**

| Status           | Description                                                                                                                              |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| NOT\_INITIALIZED | Flagship SDK has not been started or initialized successfully.                                                                           |
| INITIALIZING     | Flagship SDK is initializing.                                                                                                            |
| PANIC            | Flagship SDK is ready but is running in Panic mode: All visitor's features are disabled except 'fetchFlags' which refreshes this status. |
| INITIALIZED      | Flagship SDK is ready to use.                                                                                                            |

## FlagshipConfig

This class aims to help you to configure the SDK via the following two available config implementations: **DecisionApi** and **Bucketing**. **See** [**Decision Mode**](https://docs.abtasty.com/server-side/concepts/decision-mode) **section**.

### `withLogManager`

The `withLogManager` function of the **FlagshipConfig** class, set a custom implementation of [**LogManager**](#withlogmanager) in order to receive logs from the SDK.

**Signature**

`fun withLogManager(customLogManager: LogManager): T`

**Parameters**

| Parameter        | Type       | Description                                                              |
| ---------------- | ---------- | ------------------------------------------------------------------------ |
| customLogManager | LogManager | Custom implementation of [LogManager](doc:android-reference#LogManager). |

**Example**

```kotlin
Flagship.start(
    getApplication(),
    "_ENV_ID_", 
    "_API_KEY_"
    FlagshipConfig.DecisionApi()
      .withLogManager(object : LogManager() {
        override fun onLog(level: Level, tag: String, message: String) {
          // Intercept SDK logs.
        }
      })
)
```

### `withLogLevel`

The `withLogLevel` function of the **FlagshipConfig** class can be used to filter logs emitted by the SDK.

**Signature**

`fun withLogLevel(level: LogManager.Level): T`

**Parameters**

| Parameter | Type             | Description            |
| --------- | ---------------- | ---------------------- |
| level     | LogManager.Level | level of log priority. |

**Example**

```kotlin
Flagship.start(
    getApplication(),
    "_ENV_ID_", 
    "_API_KEY_"
    FlagshipConfig.DecisionApi()
    	.withLogLevel(LogManager.Level.ERROR)
)
```

### `withTimeout`

The `withTimeout` function of the **FlagshipConfig** class can be used to set http request timeouts in milliseconds for api requests.

**Signature**

`withTimeout(timeout: Int): T`

**Parameters**

| Parameter | Type | Description                                                                   |
| --------- | ---- | ----------------------------------------------------------------------------- |
| timeout   | Int  | Timeout in milliseconds for connect and read timeouts. Default value is 2000. |

**Example**

```kotlin
Flagship.start(
    getApplication(),
    "_ENV_ID_", 
    "_API_KEY_"
     FlagshipConfig.DecisionApi()
    	.withLogLevel(LogManager.Level.ERROR)
)
```

### `withFlagshipStatusListener`

The `withStatusListener` function of the **FlagshipConfig** class can be used to define a new listener in order to get callback when the SDK status has changed.

**Signature**

`fun withFlagshipStatusListener(listener: ((Flagship.Status) -> Unit)): T`

**Parameters**

| Parameter | Type                         | Description                                   |
| --------- | ---------------------------- | --------------------------------------------- |
| listener  | ((Flagship.Status) -> Unit)) | Lambda to invoke when SDK Status has changed. |

**Example**

```kotlin
Flagship.start(
    getApplication(),
    "_ENV_ID_", 
    "_API_KEY_",
    FlagshipConfig.DecisionApi()
      .withStatusListener { newStatus ->
          println("NEW STATUS = " + newStatus)
      }
)
```

### `withOnVisitorExposed`

The `withOnVisitorExposed` function of the **FlagshipConfig** class can be used to invoke a lambda when a visitor has been exposed to a campaign **Flag**. It is useful to centralize Flag exposition before sending them to third party tools.

**Signature**

`fun withOnVisitorExposed(onVisitorExposed: ((VisitorExposed, ExposedFlag<*>) -> (Unit))): T`

**Parameters**

| Parameter | Type                         | Description                                   |
| --------- | ---------------------------- | --------------------------------------------- |
| listener  | ((Flagship.Status) -> Unit)) | Lambda to invoke when SDK Status has changed. |

**Example**

```kotlin
Flagship.start(
    getApplication(),
    "_ENV_ID_", 
    "_API_KEY_"
    FlagshipConfig.DecisionApi()
        .withOnVisitorExposed { visitorExposed, exposedFlag ->
        // Send data to third party tool
    }
)
```

### `withCacheManager`

The `withCacheManager` function of the **FlagshipConfig** class can be used to provide a custom cache manager. Implement the **IVisitorCacheImplementation** interface to cache Visitor data or/and **IHitCacheImplementation** to cache Hits data. See [CacheManager](doc:android-reference#cachemanager)

**Signature**

`fun withCacheManager(customCacheManager: CacheManager?): T`

**Parameters**

| Parameter          | Type          | Description                             |
| ------------------ | ------------- | --------------------------------------- |
| customCacheManager | CacheManager? | Custom implementation of cache manager. |

**Example**

```kotlin
Flagship.start(
    getApplication(),
    "_ENV_ID_", 
    "_API_KEY_"
    FlagshipConfig.DecisionApi()
      .withCacheManager(object : CacheManager(), IVisitorCacheImplementation, IHitCacheImplementation {
          override fun cacheHits(hits: HashMap<String, JSONObject>) {
            // Cache hits in your own database.
          }

          override fun lookupHits(): HashMap<String, JSONObject> {
            // Load hits from your own database.
          }

          override fun flushHits(hitIds: ArrayList<String>) {
            // Delete hits from your own database.
          }

          override fun flushAllHits() {
            // Delete all hits in your own database.
          }

          override fun cacheVisitor(visitorId: String, data: JSONObject) {
             // Cache visitor data in your own database.
          }

          override fun lookupVisitor(visitorId: String): JSONObject {
            // Load visitor data from  your own database.
          }

          override fun flushVisitor(visitorId: String) {
              // Delete visitor data from  your own database.
          }
    })
)
```

\\

### `withTrackingManagerConfig`

The `withTrackingManagerConfig` function of the **FlagshipConfig** class can be used to Specify a custom tracking manager configuration. See [TrackingManagerConfig](doc:android-reference#trackingmanagerconfig).

**Signature**

`fun withTrackingManagerConfig(trackingManagerConfig: TrackingManagerConfig): T`

**Parameters**

| Parameter             | Type                  | Description                             |
| --------------------- | --------------------- | --------------------------------------- |
| trackingManagerConfig | TrackingManagerConfig | Custom implementation of cache manager. |

**Example**

```kotlin
Flagship.start(
    getApplication(),
    "_ENV_ID_", 
    "_API_KEY_"
    FlagshipConfig.DecisionApi()
        .withTrackingManagerConfig(TrackingManagerConfig(
            cachingStrategy = CacheStrategy.PERIODIC_CACHING,
            closingStrategy = ClosingStrategy.CACHE_PENDING_HITS,
            batchTimeInterval = 20000,
            maxPoolSize = 20
    ))
)
```

## Visitor

The `Visitor` class represents a unique user within your application. It is useful to manage visitor's data and fetching the corresponding flags from the [Flagship platform](https://app.flagship.io/login) .

A new visitor instance can be created using the [newVisitor](doc:android-reference#newvisitor) method from the Flagship class which returns a Visitor [Builder](doc:android-reference#visitorbuilder) class.

### `setConsent`

Specify if the visitor has consented for personal data usage. When false some features will be deactivated, cache will be deactivated and cleared.

**Signature**

`fun setConsent(hasConsented: Boolean)`

**Parameters**

| Parameter    | Type    | Description                                                                          |
| ------------ | ------- | ------------------------------------------------------------------------------------ |
| hasConsented | Boolean | Set to true when the visitor has consented for personal data usage, false otherwise. |

**Example**

```kotlin
visitor.setConsent(false)
```

### `hasConsented`

Return true if the visitor has given his consent for private data usage, false otherwise.

**Signature**

`fun hasConsented(): Boolean`

**Example**

```kotlin
val hasConsented = visitor.hasConsented()
```

### `updateContext`

Update the visitor context values, matching the given keys, used for targeting. A new context value associated with this key will be created if there is no previous matching value. Context keys must be String, and values types must be one of the following : Number, Boolean, String.

{% hint style="info" %}
📘 Refresh Flags

When Visitor's context is changed, it may target different campaigns so assigned flags should be refreshed by calling the `fetchFlags()` function afterward.
{% endhint %}

**Signature**

`fun <T> updateContext(key: String, value: T)`

**Parameters**

| Parameter | Type   | Description                                                                  |
| --------- | ------ | ---------------------------------------------------------------------------- |
| key       | String | Context key to update.                                                       |
| value     | T      | New value for the given context key. Must be Number, Boolean or String type. |

**Example**

```kotlin
visitor.updateContext("returning_visitor", true)
```

**Signature**

`fun updateContext(context: HashMap<String, Any>)`

\
**Parameters**

| Parameter | Type    | Description                                                                                                            |
| --------- | ------- | ---------------------------------------------------------------------------------------------------------------------- |
| context   | HashMap | Initial context HashMap. keys must be String, and values types must be one of the following : Number, Boolean, String. |

**Example**

```kotlin
visitor.updateContext(hashMapOf("returning_visitor" to true, "visitor_landing_page" to "https://www.mydomain.com"))
```

**Signature**

`fun <T> updateContext(flagshipContext: FlagshipContext<T>, value: T)`

**Parameters**

| Parameter       | Type            | Description                                                                             |
| --------------- | --------------- | --------------------------------------------------------------------------------------- |
| flagshipContext | FlagshipContext | Flagship predefined context key.                                                        |
| value           | T               | New value for the given predefined context key. Must be Number, Boolean or String type. |

**Example**

```kotlin
   visitor.updateContext(FlagshipContext.CARRIER_NAME, "free")
```

### `clearContext`

Clear all the visitor context values used for targeting.

{% hint style="info" %}
📘 Refresh Flags

When Visitor's context is changed, it may target different campaigns so assigned flags should be refreshed by calling the `fetchFlags()` function afterward.
{% endhint %}

**Signature**

`fun clearContext()`

**Example**

```kotlin
visitor.clearContext()
```

### `fetchFlags`

This function will fetch campaigns flags from campaigns that target visitor's context.

**Signature**

`fun fetchFlags(): Deferred<IVisitor>`

**Example**

```kotlin
runBlocking {
    visitor.fetchFlags().await()
}
```

### `getFlag`

This function will return a flag object containing the current value returned by Flagship and the associated campaign information. If the key is not found an empty Flag object with the default value will be returned. See [Flag](#flag) for more information.

**Signature**

`fun getFlag(key: String)`

**Parameters**

| Parameter | Type   | Description                           |
| --------- | ------ | ------------------------------------- |
| key       | String | Key associated with the desired flag. |

**Example**

```kotlin
val displayNewFeatureFlag = visitor.getFlag("isNewFeatureEnabled")
```

### `getFlags`

This function will return a FlagCollection containing the all the current flags returned by Flagship and the associated campaign information. See [FlagCollection](#flag-collection) for more information.

**Signature**

`fun getFlags(): FlagCollection`

**Example**

```kotlin
val allFlags = visitor.getFlags()
```

###

### `sendHit`

This function will send a Hit to Flagship collect to feed campaign reporting.

**Signature**

`fun <T> sendHit(hit: Hit<T>)`

**Parameters**

| Parameter | Type | Description                          |
| --------- | ---- | ------------------------------------ |
| hit       | Hit  | Hit to sent to the Flagship collect. |

**Example**

```kotlin
visitor.sendHit(Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket"))
```

### `authenticate`

Tag the current visitor as authenticated, This will insure to keep the same experience once the visitor is logged.

{% hint style="info" %}
📘 Refresh Flags

When authentication status is changed, it may target different campaigns so assigned flags should be refreshed by calling the `fetchFlags()` function afterward.
{% endhint %}

**Signature**

`fun authenticate(visitorId: String)`

**Parameters**

| Parameter | Type   | Description                                     |
| --------- | ------ | ----------------------------------------------- |
| visitorId | String | Unique id of the current authenticated visitor. |

**Example**

```kotlin
visitor.authenticate("logged_visitor_id")
```

### `unAuthenticate`

Tag the current visitor as authenticated, This will insure to keep the same experience once the visitor is disconnected.

{% hint style="info" %}
📘 Refresh Flags

When authentication status is changed, it may target different campaigns so assigned flags should be refreshed by calling the `fetchFlags()` function afterward.
{% endhint %}

**Signature**

`fun unauthenticate()`

**Example**

```kotlin
visitor.unAuthenticate()
```

### `collectEmotionsAIEvents`

Start collecting events for the [EmotionAI Feature](https://github.com/flagship-io/Gitbook/blob/main/SDKs/android-sdk/android-400-beta1/emotion-ai/README.md#/) if it is enabled on platform side. Returns a Job with a boolean result meaning EmotionsAI collect has ended successfully or not. This feature requires a feature activation plan on the platform side, contact us to know more about. When full plan is enabled the EmotionsAI scoring will be automatically added to your visitor context and in local cache.

{% hint style="info" %}
📘 Notes

This method needs the SDK to be initialized successfully and to have the visitor's consent, and that there is no previous score already present in the cache to run.
{% endhint %}

**Signature**

`fun collectEmotionsAIEvents(activity: Activity? = null): Deferred<Boolean>`

**Parameters**

| Parameter | Type     | Description                                                                                                                                                                      |
| --------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| activity  | Activity | The SDK will listen activities changes by setting a WindowCallback but it is possible to pass the current activity reference where Emotion AI events need to be collected first. |

**Example**

```kotlin
visitor.collectEmotionsAIEvents(this@MainActivity)
```

## Visitor.Builder

This class is an helper for Visitor instance creation.

Specify if the visitor is authenticated or anonymous for [experience continuity](https://docs.abtasty.com/server-side/sdks/android/android/android-reference).

**Signature**

`fun isAuthenticated(isAuthenticated: Boolean): Builder`

**Parameters**

| Parameter       | Type    | Description                                                                 |
| --------------- | ------- | --------------------------------------------------------------------------- |
| isAuthenticated | Boolean | boolean, true for an authenticated visitor, false for an anonymous visitor. |

**Example**

```kotlin
val visitor = Flagship.newVisitor("visitor_uuid", true)
  .isAuthenticated(true)
  .build()
```

### `context`

Specify visitor initial context key / values used for tar campaign targeting. Context keys must be String, and values types must be one of the following : Number, Boolean, String.

**Signature**

`fun context(context: HashMap<String, Any>): Builder`

**Parameters**

| Parameter | Type    | Description                                                                                                            |
| --------- | ------- | ---------------------------------------------------------------------------------------------------------------------- |
| context   | HashMap | Initial context HashMap. keys must be String, and values types must be one of the following : Number, Boolean, String. |

**Example**

```kotlin
 val visitor = Flagship.newVisitor("visitor_uuid", true)
  	.context(hashMapOf("isVIP" to true))
  	.build()
```

### `onFlagStatusChanged`

Set a FlagStatusChanged callback to be notified when Flags are out of date and need to be fetched or when flags have been successfully fetched. More info on [OnFlagStatusChanged](#onflagstatuschanged-1).

**Signature**

`fun onFlagStatusChanged(onFlagStatusChanged: OnFlagStatusChanged): Builder`

**Parameters**

| Parameter           | Type                | Description                                      |
| ------------------- | ------------------- | ------------------------------------------------ |
| onFlagStatusChanged | OnFlagStatusChanged | Implementation of OnFlagStatusChanged interface. |

**Example**

```kotlin
 val visitor = Flagship.newVisitor("visitor_abcd", true)
  .onFlagStatusChanged(object : OnFlagStatusChanged {
    override fun onFlagStatusChanged(newStatus: FlagStatus) {
      //todo
    }

    override fun onFlagStatusFetchRequired(reason: FetchFlagsRequiredStatusReason) {
      //todo
    }

    override fun onFlagStatusFetched() {
      //todo
    }
  })
  .build()
```

### `build`

Build the visitor instance.

**Signature**

`fun build(): Visitor`

**Example**

```kotlin
 val visitor = Flagship.newVisitor("visitor_uuid", true)
  	.isAuthenticated(true)
  	.context(hashMapOf("isVIP" to true))
  	.build()
```

## Visitor.Instance

This enum class allows to define how Flagship SDK should handle the newly create visitor instance.

**Values**

| Status           | Description                                                                                                                                                                                                                                                                                         |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| SINGLE\_INSTANCE | The newly created visitor instance will be returned and saved into the Flagship singleton. Call `Flagship.getVisitor()` to retrieve the instance. This option should be adopted on applications that handle only one visitor at the same time. This is the default value when a visitor is created. |
| NEW\_INSTANCE    | The newly created visitor instance wont be saved and will simply be returned. Any previous visitor instance will have to be recreated. This option should be adopted on applications that handle multiple visitors at the same time.                                                                |

## Flag

This class represents a flag in the `Flagship SDK`. It helps you retrieve the flag value, access its metadata, expose the flag, verify the flag's existence, and get the flag status with the following API.

A Flag instance will be returned when the function `[getFlag](doc:android-reference#getflag)` from the Visitor class is called.

### `value`

Return and consume the current value for this flag or return default value when the flag doesn't exist or when the current flag value type and default value type mismatch. Consuming the value will allow flag activation.

**Signature**

`inline fun <reified T: Any?> value(defaultValue: T?, visitorExposed: Boolean = true): T?`

**Parameters**

| Parameter      | Type    | Description                                                                                                                                                                                                                                                                                 |
| -------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| defaultValue   | T?      | Fallback value for this Flag when it does not exist in Flagship, or when type mismatch with the existing one.                                                                                                                                                                               |
| visitorExposed | Boolean | Tells Flagship the user have been exposed and have seen this flag. This will increment the visits for the current variation on your campaign reporting. Default value is true. If needed, it is possible to set this param to false and call userExposed() afterward when the user sees it. |

**Example**

```kotlin
val isNewFeatureEnabledFlag = visitor.getFlag("isNewFeatureEnabled", false)
val displayNewFeature = isNewFeatureEnabledFlag.value()

when (displayNewFeature) {
  true -> {
    //Display the feature
  }
  else -> {
    //Hide the feature
  }
}
```

### `metadata`

Return the campaign information metadata or an Empty flag metadata object if the flag doesn't exist.

**Signature**

`fun metadata(): FlagMetadata`

**Example**

```kotlin
val isNewFeatureEnabledMetadata = visitor.getFlag("isNewFeatureEnabled", false)
  .metadata()
```

### `visitorExposed`

Tells Flagship the user have been exposed and have seen this flag. This will increment the visits for the current variation on your campaign reporting. Only Flags whose value was consumed with value() beforehand will be exposed.

**Signature**

`fun visitorExposed()`

**Example**

```kotlin
val homeScreenLabelFlag = visitor.getFlag("homeScreenLabel", false)
val displayNewFeature = homeScreenLabelFlag.value(false)
//display new label
homeScreenLabelFlag.visitorExposed())
```

### `exists`

Check and return true if the current flag exists in Flagship SDK, false otherwise.

**Signature**

`fun exists(): Boolean`

**Example**

```kotlin
val doesFlagExist = visitor.getFlag("homeScreenLabel", false).exists()
```

### `status`

Return the status for this Flag. See [FlagStatus](#flagstatus).

**Signature**

`fun status(): FlagStatus`

**Example**

```kotlin
val myFlagStatus visitor.getFlag("myFlag", "default").status()
```

## Flag collection

This class holds a collection of Flag and helpers to manipulate them.

### `keys`

Return all the Flag keys contained in the collection.

**Signature**

`fun keys(): MutableSet<String>`

**Example**

```kotlin
visitor.getFlags().keys()
```

### `get`

Return a Flag from the collection.

**Signature**

`operator fun get(key: String): Flag`

**Example**

```kotlin
val flagCollection = visitor.getFlags()
val flag = flagCollection["my_flag"]
val flag2 = flagCollection.get("my_flag_2")
```

Expose all the flags in the collection. Only the ones whose value has been consumed will be exposed.

**Signature**

`fun exposeAll()`

**Example**

```kotlin
visitor.getFlags().exposeAll()
```

### `filter`

Return a new FlagCollection matching the given predicate.

**Signature**

`fun filter(predicate: (Map.Entry<String, Flag>) -> Boolean): FlagCollection`

**Parameters**

| Parameter | Type                                  | Description                         |
| --------- | ------------------------------------- | ----------------------------------- |
| predicate | (Map.Entry\<String, Flag>) -> Boolean | Predicate to filter the collection. |

**Example**

```kotlin
val appCampaignFlags = visitor.getFlags().filter { (k, f) -> flag.metadata().campaignName == "app" }
```

### `metadata`

Return a map of Flag FlagMetadata from the collection.

**Signature**

`fun metadata(): Map<String, FlagMetadata>`

**Example**

```kotlin
val flagCollection = visitor.getFlags()
val flagCollectionMetadata = flagCollection.metadata()
```

### `toJSON`

Return the collection Flags metadata as JSONObject.

**Signature**

`fun toJSON(): JSONObject`

**Example**

```kotlin
val flagCollection = visitor.getFlags()
val jsonFlagCollection = flagCollection.toJSON()
```

### `iterator`

Return a FlagCollection iterator.

**Signature**

`operator fun iterator(): Iterator<Pair<String, Flag>>`

**Example**

```kotlin
val flagCollection = visitor.getFlags()
for ((k, v) in flagCollection) {
  //
}
```

### `size`

Return the collection size.

**Signature**

`fun size(): Int`

**Example**

```kotlin
val flagCollectionSize = visitor.getFlags().size()
```

## FlagMetadata

This class holds all flag campaign information. FlagMetadata object can be returned by calling the `[metadata](doc:android-reference#metadata)()` function from a Flag instance.

### Properties

| Property           | Type   | Description                                                              |
| ------------------ | ------ | ------------------------------------------------------------------------ |
| campaignId         | String | Flag use-case id.                                                        |
| campaignName       | String | Flag use-case name defined in the platform from which the Flag comes.    |
| campaignType       | String | Flag use-case type selected in the platform from which the Flag comes.   |
| variationGroupId   | String | Id of the variation group from which the Flag comes.                     |
| variationGroupName | String | Name of the Flag variation group from which the Flag comes.              |
| variationId        |        | Id of the variation from which the Flag comes.                           |
| variationName      |        | Name of the variation defined on the platform from which the Flag comes. |
| slug               |        | Flag use-case custom slug defined in the platform.                       |
| isReference        |        | Is the Flag from the reference variation.                                |
| allocation         |        | Variation allocation.                                                    |

### `exists`

Check and return true if the current flag exists and has metadatas in Flagship SDK, false otherwise.

**Signature**

`fun exists(): Boolean`

**Example**

```kotlin
val doesFlagMetadataExist = visitor.getFlag("homeScreenLabel", false).metadata().exists()
```

### `toJSON`

Transform the current FlagMetadata instance into a json object containing all the properties.

**Signature**

`fun toJSON(): JSONObject`

**Example**

```kotlin
val flagMetadataJSON = visitor.getFlag("homeScreenLabel", false).metadata().toJSON()
```

## Hit

This super class helps you track your users in your application and learn how to build hits in order to feed campaign goals. For more information about our measurement protocol, read our [Universal Collect documentation](https://docs.abtasty.com/server-side/concepts/universal-collect-1).

There are five different types of Hits available: Page, Screen, Event, Transaction, Item and all have common options.

### `withIp`

Set the current user public ip.

**Signature**

`fun withIp(ip: String): T`

**Parameters**

| Parameter | Type   | Description                  |
| --------- | ------ | ---------------------------- |
| ip        | String | Current visitor's public IP. |

**Example**

```kotlin
 visitor.sendHit(
   Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
     .withId("8.8.8.8")
 )
```

### `withResolution`

Set the current device screen resolution.

**Signature**

`fun withResolution(width: Int, height: Int): T`

**Parameters**

| Parameter | Type | Description                             |
| --------- | ---- | --------------------------------------- |
| width     | Int  | Current visitor's device screen width.  |
| height    | Int  | Current visitor's device screen height. |

**Example**

```kotlin
visitor.sendHit(
  Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
    .withResolution(1920, 1080)
)
```

### `withSessionNumber`

Set the current visitor session number.

**Signature**

`fun withSessionNumber(number: Int): T`

**Parameters**

| Parameter | Type | Description                     |
| --------- | ---- | ------------------------------- |
| number    | Int  | Current visitor session number. |

**Example**

```kotlin
visitor.sendHit(
  Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
    .withSessionNumber(3)
)
```

### `withLocale`

Set the current user device locale.

**Signature**

`fun withLocale(locale: String): T`

**Parameters**

| Parameter | Type   | Description                                           |
| --------- | ------ | ----------------------------------------------------- |
| locale    | String | Current user device locale (must be valid iso3 code). |

**Example**

```kotlin
visitor.sendHit(
  Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
    .withLocale("fra")
)
```

## Page

Hit to send when a user sees a web page.

**Parameters**

| Parameter | Type   | Description |
| --------- | ------ | ----------- |
| location  | String | Page url.   |

**Example**

```kotlin
import com.abtasty.flagship.hits.Page

visitor.sendHit(
  Page("www.domain.com")
)
```

## Screen

Hit to send when a user sees an interface.

**Parameters**

| Parameter | Type   | Description     |
| --------- | ------ | --------------- |
| location  | String | Interface name. |

**Example**

```kotlin
import com.abtasty.flagship.hits.Screen

visitor.sendHit(
  Screen("PaymentActivity")
)
```

## Event

Hit which represents an event. Can be a anything you want : for example a click or a newsletter subscription.

**Parameters**

| Parameter | Type          | Description                               |
| --------- | ------------- | ----------------------------------------- |
| category  | EventCategory | Category of the event.                    |
| action    | String        | Event action matching your campaign goal. |

**Example**

```kotlin
import com.abtasty.flagship.hits.Event

visitor.sendHit(
  Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
)
```

### `withEventLabel`

Set a label for this event.

**Signature**

`fun withEventLabel(label: String): Event`

**Parameters**

| Parameter | Type   | Description           |
| --------- | ------ | --------------------- |
| label     | String | Label for this event. |

**Example**

```kotlin
import com.abtasty.flagship.hits.Event

visitor.sendHit(
  Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
    .withEventLabel("Go to basket")
)
```

### `withEventValue`

Set a value for this event. Must be non-negative Int.

**Signature**

`fun withEventValue(value: Int): Event`

**Parameters**

| Parameter | Type | Description           |
| --------- | ---- | --------------------- |
| value     | Int  | Value for this event. |

**Example**

```kotlin
import com.abtasty.flagship.hits.Event

visitor.sendHit(
  Event(Event.EventCategory.ACTION_TRACKING, "click_on_basket")
    .withEventValue(3)
)
```

## Transaction

Hit to send when a user complete a transaction.

**Parameters**

| Parameter     | Type   | Description                                   |
| ------------- | ------ | --------------------------------------------- |
| transactionId | String | Transaction unique identifier.                |
| affiliation   | String | Affiliation name matching your campaign goal. |

### `withTotalRevenue`

Set the total revenue associated with the transaction. This value should include any shipping or tax costs.

**Signature**

`fun withTotalRevenue(revenue: Float): Transaction`

**Parameters**

| Parameter | Type  | Description    |
| --------- | ----- | -------------- |
| revenue   | Float | Total revenue. |

**Example**

```kotlin
import com.abtasty.flagship.hits.Transaction

visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withTotalRevenue(99.9f)
)
```

### `withShippingCosts`

Set the total shipping cost of the transaction.

**Signature**

`fun withShippingCosts(shipping: Float): Transaction`

**Parameters**

| Parameter | Type  | Description                  |
| --------- | ----- | ---------------------------- |
| shipping  | Float | Total of the shipping costs. |

**Example**

```kotlin
visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withShippingCosts(4.99f)
)
```

### `withShippingMethod`

Set the shipping method.

**Signature**

`fun withShippingMethod(shippingMethod: String): Transaction`

**Parameters**

| Parameter      | Type  | Description                               |
| -------------- | ----- | ----------------------------------------- |
| shippingMethod | Float | Shipping method used for the transaction. |

**Example**

```kotlin
visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withShippingMethod("Chrono 48")
)
```

### `withTaxes`

Set the total taxes of the transaction.

**Signature**

`fun withTaxes(taxes: Float): Transaction`

**Parameters**

| Parameter | Type  | Description  |
| --------- | ----- | ------------ |
| taxes     | Float | Total taxes. |

**Example**

```kotlin
visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withTaxes(9.99f)
)
```

### `withCurrency`

Set the currency used for all transaction currency values. Value should be a valid ISO 4217 currency code.

**Signature**

`fun withCurrency(currency: String): Transaction`

**Parameters**

| Parameter | Type   | Description                        |
| --------- | ------ | ---------------------------------- |
| currency  | String | Currency used for the transaction. |

**Example**

```kotlin
visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withCurrency("EUR")
)
```

### `withPaymentMethod`

Set the payment method for the transaction.

**Signature**

`fun withPaymentMethod(paymentMethod: String): Transaction`

**Parameters**

| Parameter     | Type   | Description                              |
| ------------- | ------ | ---------------------------------------- |
| paymentMethod | String | Payment method used for the transaction. |

**Example**

```kotlin
visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withPaymentMethod("credit_card")
)
```

### `withItemCount`

Set the number of items for the transaction.

**Signature**

`fun withItemCount(itemCount: Int): Transaction`

**Parameters**

| Parameter | Type | Description                |
| --------- | ---- | -------------------------- |
| itemCount | Int  | Number of purchased items. |

**Example**

```kotlin
visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withItemCount(2)
)
```

### `withCouponCode`

Set the coupon code used by the customer for the transaction.

**Signature**

`fun withCouponCode(coupon: String): Transaction`

**Parameters**

| Parameter | Type   | Description                           |
| --------- | ------ | ------------------------------------- |
| coupon    | String | Coupon code used for the transaction. |

**Example**

```kotlin
visitor.sendHit(
  Transaction("942B42042CC", "affiliation")
    .withCouponCode("COUPON10")
)
```

## Item

Hit to send to associated items to a transaction. Items must be sent after the corresponding transaction.

**Parameters**

| Parameter     | Type   | Description                                |
| ------------- | ------ | ------------------------------------------ |
| transactionId | String | Id of the transaction linked to this item. |
| productName   | String | Name of the product.                       |
| productSku    | String | Item code or SKU.                          |

**Example**

```kotlin
import com.abtasty.flagship.hits.Item

visitor.sendHit(
  Item("942B42042CC", "Item", "U20398")
)
```

### `withItemPrice`

Set the item price.

**Signature**

`fun withItemPrice(price: Float): Item`

**Parameters**

| Parameter | Type  | Description |
| --------- | ----- | ----------- |
| price     | Float | Item price. |

**Example**

```kotlin
visitor.sendHit(
  Item("942B42042CC", "Item", "U20398")
    .withItemPrice(39.99f)
)
```

### `withItemQuantity`

Set the number of item purchased.

**Signature**

`fun withItemCategory(category: String): Item`

**Parameters**

| Parameter | Type | Description               |
| --------- | ---- | ------------------------- |
| quantity  | Int  | Number of purchased item. |

**Example**

```kotlin
visitor.sendHit(
  Item("942B42042CC", "Item", "U20398")
    .withItemQuantity(2)
)
```

### `withItemCategory`

Set the item category.

**Signature**

`fun withItemCategory(category: String): Item`

**Parameters**

| Parameter | Type   | Description           |
| --------- | ------ | --------------------- |
| category  | String | Category of the item. |

**Example**

```kotlin
visitor.sendHit(
  Item("942B42042CC", "Item", "U20398")
    .withItemCategory("Furniture")
)
```

## CacheManager

By default the SDK implements a DefaultCacheManager which uses a local SQLiteDatabase. The CacheManager is an abstract class to implement in order to use your own caching solution. Implement [IVisitorCacheImplementation](#ivisitorcacheimplementation) and/or [IHitCacheImplementation](#ihitcacheimplementation) interfaces to provide a custom cache implementation for visitor's data and hits emitted by visitors.

The purpose of implementing cache is to prevent re-allocation in bucketing mode and prevent any data loss when the SDK is running offline. See more details in [Managing cache.](https://docs.abtasty.com/server-side/sdks/key-features/managing-cache)

**Parameters**

| Parameter                 | Type | Description                                              |
| ------------------------- | ---- | -------------------------------------------------------- |
| visitorCacheLookupTimeout | Long | Reading timeout for cached visitor data in milliseconds. |
| hitsCacheLookupTimeout    | Long | Reading timeout for cached hits in milliseconds.         |

## IVisitorCacheImplementation

This interface specifies the methods to implement in order to cache visitors data.

Visitor cache is used for: retrieving campaign flags while offline, preventing re-allocation in bucketing mode and is used by some feature to work.

### `cacheVisitor`

This method is called when the SDK need to upsert (insert or update) current visitor information into the database.

**Signature**

`fun cacheVisitor(visitorId : String, data : JSONObject)`

**Parameters**

| Parameter | Type       | Description                                                   |
| --------- | ---------- | ------------------------------------------------------------- |
| visitorId | String     | Unique visitor identifier whom information need to be cached. |
| data      | JSONObject | Visitor information to store in your database.                |

### `lookupVisitor`

This method is called when the SDK need to load visitor information from the database.

**Signature**

`fun lookupVisitor(visitorId: String) : JSONObject`

**Parameters**

| Parameter | Type   | Description                                                                     |
| --------- | ------ | ------------------------------------------------------------------------------- |
| visitorId | String | Unique visitor identifier whom information need to be loaded from the database. |

### `flushVisitor`

This method is called when visitor information should be cleared from the database.

**Signature**

`fun flushVisitor(visitorId: String)`

**Parameters**

| Parameter | Type   | Description                                                                             |
| --------- | ------ | --------------------------------------------------------------------------------------- |
| visitorId | String | Unique visitor identifier whom cached information need to be cleared from the database. |

**Example**

```kotlin
Flagship.start(
  getApplication(), _ENV_ID_, _API_KEY_, FlagshipConfig.Bucketing()
    .withCacheManager(object : CacheManager(), IVisitorCacheImplementation {
      
      override fun cacheVisitor(visitorId: String, data: JSONObject) {
        // Cache visitor information in your own database.
      }

      override fun lookupVisitor(visitorId: String): JSONObject {
        // Load visitor information from your own database.
      }

      override fun flushVisitor(visitorId: String) {
        // Flush visitor information from your own database.
      }

    })
)
```

## IHitCacheImplementation

This interface defines the methods to implement in order to cache hits for flagship SDK. Saving hits prevent any data loss while running offline.

### `cacheHits`

This method is called when the SDK need to save hits into the database.

**Signature**

`fun cacheHits(hits: HashMap<String, JSONObject>)`

**Parameters**

| Parameter | Type                         | Description                     |
| --------- | ---------------------------- | ------------------------------- |
| hits      | HashMap\<String, JSONObject> | hits to store in your database. |

### `lookupHits`

This method is called when the SDK need to load hits from the database to sent them again.

**Warning** : Hits must be deleted from the database before being returned so your database remains clean and so hits can be inserted again if they fail to be sent a second time.

**Signature**

`fun lookupHits(): HashMap<String, JSONObject>`

### `flushHits`

This method is called when hits need to be removed from the database.

**Signature**

`fun flushHits(hitIds: ArrayList<String>)`

**Parameters**

| Parameter | Type               | Description                              |
| --------- | ------------------ | ---------------------------------------- |
| hitIds    | ArrayList\<String> | List of hit ids that need to be removed. |

### `flushAllHits`

This method is called when the Flagship SDK needs to flush all the hits from cache.

**Signature**

`fun flushAllHits()`

Example

```kotlin
 Flagship.start(
   getApplication(), _ENV_ID_, _API_KEY_, FlagshipConfig.Bucketing()
   	.withCacheManager(object : CacheManager(), IHitCacheImplementation {
   
       	override fun cacheHits(hits: HashMap<String, JSONObject>) {
       		// Cache hits in your own database.
     		}

    		override fun lookupHits(): HashMap<String, JSONObject> {
      		// Remove and return hits from your own database
    		}

    		override fun flushHits(hitIds: ArrayList<String>) {
      		// remove hits from your own database.
    		}

    		override fun flushAllHits() {
      		// remove all hits from your own database.
    		}
		})
)
```

## TrackingManagerConfig

This class configure the Flagship SDK Tracking Manager which gathers all visitors emitted hits in a pool and fire them in batch requests at regular time intervals withing a dedicated thread.

**Parameters**

| Parameter         | Type            | Description                                                                                                                                                |
| ----------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| cachingStrategy   | CacheStrategy   | Define the strategy to use for hits caching. It relies on the CacheManager provided in FlagshipConfig. Default value is CacheStrategy.CONTINUOUS\_CACHING. |
| closingStrategy   | ClosingStrategy | Define the strategy to use for remaining hits in the pool when stopping Flagship. Default value is ClosingStrategy.CACHE\_PENDING\_HITS.                   |
| batchTimeInterval | Long            | Define a time delay between each batched hit requests in milliseconds. Default value is 10000.                                                             |
| maxPoolSize       | Int             | Define a max hit pool size that will trigger a batch request once reached. Default value is 10.                                                            |

#### CachingStrategy

This class specifies the hits caching strategy to adopt into the TrackingManager and relies on the IHitCacheImplementation class that must be implemented in the CacheManager. Depending on the strategy the TrackingManager will request the CacheManager to CACHE, LOOK-UP or FLUSH hits from the linked database.

**Value**

| Parameter           | Description                                                                                                                                                                                                                                                                                                         |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| CONTINUOUS\_CACHING | Hits will be continuously cached and flushed from the database. The database linked to the HitCacheImplementation class implemented in the provided CacheManager will be required each time time a hit is added or flushed from the TrackingManager pool.                                                           |
| PERIODIC\_CACHING   | Hits will be cached and flushed from the database periodically.The database linked to the IHitCacheImplementation class implemented in the provided CacheManager will be required to cache/look-up/flush hits at regular time intervals. The time intervals relies on the TrackingManager 'batch intervals' option. |

#### ClosingStrategy

This class specifies the hits closing strategy to adopt when the SDK is closing.

**Value**

| Parameter            | Description                                                                        |
| -------------------- | ---------------------------------------------------------------------------------- |
| CACHE\_PENDING\_HITS | Remaining Hits in the pool will be cached into the CacheManager provided database. |
| BATCH\_PENDING\_HITS | Remaining Hits in the pool will be sent as Batch.                                  |

## Appendix

### Predefined context keys

The Flagship SDK contains predefined user context keys.

The keys marked as **Yes** in the **Auto-set by SDK** column will be automatically set, while the ones marked as **No** need to be set by the client.

{% hint style="info" %}
📘 Check values

Check the values sent by the SDK by enabling the logs.
{% endhint %}

You can overwrite these keys at any time. The key-value pairs will be sent to the server in the user context and can be edited in the Persona section of the Flagship platform.

| SDK Variable Name              | Description                                            | Context variable name                 | Type    | Auto-set by SDK | Example                                      |
| ------------------------------ | ------------------------------------------------------ | ------------------------------------- | ------- | --------------- | -------------------------------------------- |
| FIRST\_TIME\_INIT              | First init of the app                                  | sdk\_firstTimeInit                    | Boolean | Yes             | TRUE (FALSE if the init isn't the first one) |
| LOCALE                         | Language of the device                                 | sdk\_deviceLanguage                   | String  | Yes             | fr\_FR                                       |
| DEVICE\_TYPE                   | Tablette / Mobile                                      | sdk\_deviceType                       | String  | Yes             | mobile                                       |
| DEVICE\_MODEL                  | Model of the device                                    | sdk\_deviceModel                      | String  | Yes             | samsung E1200                                |
| LOCATION\_CITY                 | City geolocation                                       | sdk\_city                             | String  | No              | toulouse                                     |
| LOCATION\_REGION               | Region geolocation                                     | sdk\_region                           | String  | No              | occitanie                                    |
| LOCATION\_COUNTRY              | Country geolocation                                    | sdk\_country                          | String  | No              | France                                       |
| LOCATION\_LAT                  | Current Latitude                                       | sdk\_lat                              | Double  | No              | 43.623647                                    |
| LOCATION\_LONG                 | Current Longitude                                      | sdk\_long                             | Double  | No              | 1.445397                                     |
| OS\_NAME                       | Name of the OS                                         | sdk\_osName                           | String  | Yes             | android / iOS                                |
| OS\_VERSION                    | Version of the OS                                      | sdk\_osVersion                        | String  | Yes             | pie                                          |
| API\_LEVEL                     | Version of the API                                     | sdk\_apiLevel                         | Integer | Yes             | 24                                           |
| ANDROID\_VERSION / IOS VERSION | Version of Android                                     | sdk\_androidVersion / sdk\_iOSVersion | String  | Yes             | 9                                            |
| MVNO / carrierName             | Name of the carrier or mobile virtual network operator | sdk\_carrierName                      | String  | Yes             | orange                                       |
| DEV\_MODE                      | Is the app in debug mode?                              | sdk\_devMode                          | Boolean | Yes             | TRUE                                         |
| VISITOR\_ID                    | Visitor\_id of the user                                | sdk\_visitorId                        | String  | Yes             | toto2000                                     |
| INTERNET\_CONNECTION           | What is the internet connection                        | sdk\_internetConnection               | String  | No              | 3g                                           |
| APP\_VERSION\_NAME             | Version name of the app                                | sdk\_versionName                      | String  | No              | 1.1.2-beta                                   |
| APP\_VERSION\_CODE             | Version code of the app                                | sdk\_versionCode                      | Integer | No              | 40                                           |
| FLAGSHIP\_VERSION              | Version of the Flagship SDK                            | sdk\_fsVersion                        | String  | Yes             | 1.1.2                                        |
| INTERFACE\_NAME                | Name of the interface                                  | sdk\_interfaceName                    | String  | No              | ProductPage                                  |

{% hint style="info" %}
📘 Override values

To overwrite the keys, use the [`updateContext`](#update-context-with-predefined-keys-of-context) method
{% endhint %}

### FlagStatus

Enum class that represents a Flag Status.

**Values**

| Status          | Description                                                                                     |
| --------------- | ----------------------------------------------------------------------------------------------- |
| NOT\_FOUND      | Flag does not exist in Flagship SDK.                                                            |
| FETCH\_REQUIRED | Flags are out of date, it is necessary to call fetchFlags() function to update them.            |
| FETCHING        | Flags are currently being fetched.                                                              |
| PANIC           | SDK is in Panic mode, all Flags will fallback with default values, exposition will be disabled. |
| FETCHED         | Flags have been fetched and are up to date.                                                     |

### OnFlagStatusChanged

This interface represents a callback which could be used to be notified by the SDK when Visitor FetchStatus have changed or when Flags. See [FlagStatus](#flagstatus).

#### `onFlagStatusChanged`

This function will be called each time the FlagStatus has changed.

**Signature**

`fun onFlagStatusChanged(newStatus: FlagStatus)`

**Parameters**

| Parameter | Type       | Description     |
| --------- | ---------- | --------------- |
| newStatus | FlagStatus | New Flag Status |

#### `onFlagStatusFetchRequired`

This function will be called each time Flags are out of date and have to be updated by calling fetchFlags().

**Signature**

`fun onFlagStatusChanged(newStatus: FlagStatus)`

**Parameters**

| Parameter | Type                           | Description           |
| --------- | ------------------------------ | --------------------- |
| reason    | FetchFlagsRequiredStatusReason | Fetch required reason |

#### `onFlagStatusFetched`

This function will be called each time Flags have been fetched and updated successfully.

**Signature**

`fun onFlagStatusChanged(newStatus: FlagStatus)`

**Parameters**

| Parameter | Type                           | Description           |
| --------- | ------------------------------ | --------------------- |
| reason    | FetchFlagsRequiredStatusReason | Fetch required reason |
