package main

import (
	"runtime"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/theme"
)

func MobileOptimizations(a fyne.App) {
	if runtime.GOOS == "android" || runtime.GOOS == "ios" {
		settings := a.Settings()
		settings.SetTheme(theme.DarkTheme())

		if runtime.GOOS == "android" {
			time.Sleep(100 * time.Millisecond)
		}

		if runtime.GOOS == "ios" {
			time.Sleep(50 * time.Millisecond)
		}
	}
}

type PerformanceMonitor struct {
	startTime time.Time
	metrics   map[string]time.Duration
}

func NewPerformanceMonitor() *PerformanceMonitor {
	return &PerformanceMonitor{
		startTime: time.Now(),
		metrics:   make(map[string]time.Duration),
	}
}

func (pm *PerformanceMonitor) StartTimer(name string) {
	pm.startTime = time.Now()
}

func (pm *PerformanceMonitor) EndTimer(name string) {
	duration := time.Since(pm.startTime)
	pm.metrics[name] = duration

	if duration > 100*time.Millisecond {
		println("Медленная операция:", name, duration)
	}
}

func (pm *PerformanceMonitor) GetMetrics() map[string]time.Duration {
	return pm.metrics
}

type MemoryOptimizer struct {
	lastGC time.Time
}

func NewMemoryOptimizer() *MemoryOptimizer {
	return &MemoryOptimizer{
		lastGC: time.Now(),
	}
}

func (mo *MemoryOptimizer) CheckMemory() {
	if time.Since(mo.lastGC) > 30*time.Second {
		if runtime.GOOS == "android" || runtime.GOOS == "ios" {
			runtime.GC()
			mo.lastGC = time.Now()
		}
	}
}

type BatteryOptimizer struct {
	lastUpdate     time.Time
	updateInterval time.Duration
}

func NewBatteryOptimizer() *BatteryOptimizer {
	interval := 5 * time.Second
	if runtime.GOOS == "android" || runtime.GOOS == "ios" {
		interval = 10 * time.Second
	}

	return &BatteryOptimizer{
		lastUpdate:     time.Now(),
		updateInterval: interval,
	}
}

func (bo *BatteryOptimizer) ShouldUpdate() bool {
	return time.Since(bo.lastUpdate) >= bo.updateInterval
}

func (bo *BatteryOptimizer) UpdateComplete() {
	bo.lastUpdate = time.Now()
}

type NetworkOptimizer struct {
	lastRequest time.Time
	minInterval time.Duration
}

func NewNetworkOptimizer() *NetworkOptimizer {
	interval := 1 * time.Second
	if runtime.GOOS == "android" || runtime.GOOS == "ios" {
		interval = 2 * time.Second
	}

	return &NetworkOptimizer{
		lastRequest: time.Now(),
		minInterval: interval,
	}
}

func (no *NetworkOptimizer) CanMakeRequest() bool {
	return time.Since(no.lastRequest) >= no.minInterval
}

func (no *NetworkOptimizer) RequestComplete() {
	no.lastRequest = time.Now()
}
