import {Meta} from '@storybook/addon-docs/blocks'

<Meta title='@dxtmisha/functional/en/Classes/CacheStatic'/>

# CacheStatic Class

Static wrapper class around Cache for global caching during code execution. Provides a singleton Cache instance accessible from anywhere in the application for cross-component data sharing and performance optimization.

## Key Features

- **Global singleton cache** — single shared Cache instance for entire application
- **Static interface** — access cache without creating instances
- **Cross-component sharing** — share cached data between different parts of application
- **Performance optimization** — reduce redundant computations across components
- **Simple API** — same interface as Cache class but accessible statically
- **Automatic lifecycle management** — Cache instance created automatically

## Basic Usage

### `get`

Synchronously retrieves data from global cache or executes callback to generate new data.

**Parameters:**
- `name: string` — unique cache name/key in global cache
- `callback: () => T` — function to execute if cache miss or invalidation
- `comparison?: any[]` — array of values for cache invalidation comparison (optional)

**Returns:** `T` — cached data or result of callback execution

```javascript
import { CacheStatic } from '@dxtmisha/functional'

// Cache expensive computation globally
const expensiveResult = CacheStatic.get('global-computation', () => {
  console.log('Performing expensive computation...')
  // Simulate heavy computation
  let sum = 0
  for (let i = 0; i < 1000000; i++) {
    sum += Math.random()
  }
  return { result: sum, timestamp: Date.now() }
})

// Accessible from anywhere in application
const sameResult = CacheStatic.get('global-computation', () => {
  console.log('This will not execute')
  return { result: 0, timestamp: 0 }
})
// Returns cached data without re-computation

// Different components can share cached data
class ComponentA {
  getData() {
    return CacheStatic.get('shared-data', () => {
      console.log('ComponentA: Loading shared data')
      return { source: 'ComponentA', data: [1, 2, 3] }
    })
  }
}

class ComponentB {
  getData() {
    return CacheStatic.get('shared-data', () => {
      console.log('ComponentB: This will not execute')
      return { source: 'ComponentB', data: [4, 5, 6] }
    })
  }
}

const compA = new ComponentA()
const compB = new ComponentB()

const dataA = compA.getData() // Executes callback
const dataB = compB.getData() // Returns cached data from ComponentA
console.log(dataA === dataB) // true - same cached object
```

## Cache Invalidation

Global cache invalidation works the same as regular Cache class:

```javascript
// Global cache with dependencies
let currentTheme = 'dark'
let currentLanguage = 'en'

const getAppConfig = () => CacheStatic.get(
  'app-config',
  () => {
    console.log(`Loading config: theme=${currentTheme}, lang=${currentLanguage}`)
    return {
      theme: currentTheme,
      language: currentLanguage,
      features: getFeaturesByTheme(currentTheme),
      translations: getTranslationsByLanguage(currentLanguage)
    }
  },
  [currentTheme, currentLanguage] // Global cache invalidates when these change
)

// First call
const config1 = getAppConfig() // Executes callback
console.log(config1.theme) // 'dark'

// Cached call
const config1Cached = getAppConfig() // Returns cached data

// Change dependency - global cache invalidates
currentTheme = 'light'
const config2 = getAppConfig() // Cache invalidated, executes callback again
console.log(config2.theme) // 'light'

function getFeaturesByTheme(theme) {
  return theme === 'dark' ? ['night-mode', 'blue-light-filter'] : ['day-mode']
}

function getTranslationsByLanguage(lang) {
  return lang === 'en' ? { hello: 'Hello' } : { hello: 'Привет' }
}
```

## Practical Examples

### Global Configuration

```javascript
class AppConfig {
  static getConfig() {
    return CacheStatic.get('app-config', () => ({
      apiUrl: process.env.API_URL || '/api',
      features: { darkMode: true, notifications: true },
      version: '1.0.0'
    }))
  }

  static isFeatureEnabled(feature) {
    return this.getConfig().features[feature] || false
  }
}

// Usage across modules
console.log(AppConfig.getConfig().version) // Loads configuration
console.log(AppConfig.isFeatureEnabled('darkMode')) // Uses cached
```

### Component Data Sharing

```javascript
class UserSession {
  static getCurrentUser() {
    return CacheStatic.get('current-user', () => ({
      id: 1,
      name: 'John Doe',
      role: 'admin',
      permissions: ['read', 'write']
    }))
  }

  static hasPermission(permission) {
    const user = this.getCurrentUser()
    return user?.permissions.includes(permission) || false
  }
}

// Usage
console.log(UserSession.getCurrentUser()) // Loads user
console.log(UserSession.hasPermission('write')) // Uses cached
```

### Cache with Invalidation

```javascript
let currentTheme = 'dark'
let language = 'en'

function getThemeConfig() {
  return CacheStatic.get(
    'theme-config',
    () => ({
      theme: currentTheme,
      colors: currentTheme === 'dark' ? ['#000', '#333'] : ['#fff', '#ccc'],
      language
    }),
    [currentTheme, language] // Invalidation on change
  )
}

console.log(getThemeConfig()) // First call
currentTheme = 'light' // Change dependency
console.log(getThemeConfig()) // Cache invalidated, recalculated
```

The CacheStatic class provides a simple way to globally cache data in applications, allowing components to efficiently share computed values and configurations.
