Source code

We have made the main source code publicly available. We hope it will be helpful as a reference for app development.

● Japanese ● ご注意 ● このページで公開しているのはDartコードのみです。アプリの動作には画像・音声・多言語テキストなどの追加データが必要なため、ここに掲載している情報だけではアプリを完全に再現することはできません。 ● アプリは継続的に機能拡張しているため、ストアで公開している最新版とコード内容が異なる場合があります。 ● コードはコピーして自由にご利用いただけますが、著作権は放棄していません。そのため、コード全体の再掲載はご遠慮ください。一部の引用や改変しての再掲載は問題ありません。個人利用・商用利用を問わず、アプリ開発の参考として自由にお使いください。 ● このコードは「お手本」として公開しているものではありません。ミニアプリとして作成しているため、変数名など細部に配慮していない箇所や誤りが含まれる可能性があります。参考程度にご覧ください。 ● 他の開発者の公開コードを参考にした部分も含まれています。アプリ開発の熟練者が書いたコードではない点もご了承ください。 ● ここはエンジニア向けの技術情報共有サービスではないため、詳細な説明は省略しています。 ● 本コードは無保証であり、動作や品質を保証するものではありません。
Copyright© エーオーシステム株式会社

● English ● Notice ● Only the Dart source code is provided on this page. Additional assets such as images, audio files, and multilingual text are required for the application to function. Therefore, the information here alone is not sufficient to fully reproduce the app. ● The app is continuously being improved, so the code published here may differ from the latest version available on the app stores. ● You are free to copy and use the code, but the copyright is not waived. For this reason, please refrain from redistributing (reposting) the entire code. Partial quotation or redistribution of modified portions is allowed. You may use the code freely for reference in your own app development, whether for personal or commercial use. ● This code is not intended to serve as a coding example or best practice. As this is a small sample app, some variable names and details may lack refinement, and there may be mistakes. Please use it only as a reference. ● Some parts of the code are based on publicly available examples from other developers. Please note that this code was not written by an expert in Android app development. ● This is not a technical knowledge-sharing service for engineers, so detailed explanations are omitted. ● The code is provided "as is" without any warranty of any kind.
Copyright© ao-system, Inc.

Last build date: 2026-05-15

name: wheellotterymachine
description: "wheellotterymachine"

publish_to: 'none'

version: 2.9.1+48

environment:
  sdk: ^3.11.5

dependencies:     #flutter pub upgrade --major-versions
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  intl: ^0.20.2               #flutter gen-l10n
  shared_preferences: ^2.2.2
  flutter_tts: ^4.2.3
  audioplayers: ^6.5.1
  google_mobile_ads: ^8.0.0
  collection: ^1.19.1
  wakelock_plus: ^1.4.0
  in_app_review: ^2.0.11
  app_tracking_transparency: ^2.0.4

dev_dependencies:
  flutter_lints: ^6.0.0
  flutter_launcher_icons: ^0.14.3    #flutter pub run flutter_launcher_icons
  flutter_native_splash: ^2.3.6     #flutter pub run flutter_native_splash:create

flutter_icons:
  android: "launcher_icon"
  ios: true
  image_path: "assets/icon/icon.png"
  adaptive_icon_background: "assets/icon/icon_back.png"
  adaptive_icon_foreground: "assets/icon/icon_fore.png"

flutter_native_splash:
  color: '#9da9f5'
  image: 'assets/image/splash.png'
  color_dark: '#9da9f5'
  image_dark: 'assets/image/splash.png'
  fullscreen: true
  android_12:
    icon_background_color: '#9da9f5'
    image: 'assets/image/splash.png'
    icon_background_color_dark: '#9da9f5'
    image_dark: 'assets/image/splash.png'

flutter:
  generate: true
  uses-material-design: true

  assets:
    - assets/image/
    - assets/sound/

import 'package:flutter/cupertino.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'package:wheellotterymachine/ad_manager.dart';

class AdBannerWidget extends StatefulWidget {
  final AdManager adManager;
  const AdBannerWidget({super.key, required this.adManager});
  @override
  State<AdBannerWidget> createState() => _AdBannerWidgetState();
}

class _AdBannerWidgetState extends State<AdBannerWidget> {
  int _lastBannerWidthDp = 0;
  bool _isAdLoaded = false;
  bool _isLoading = false;
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: LayoutBuilder(
        builder: (context, constraints) {
          final int width = constraints.maxWidth.isFinite ? constraints.maxWidth.truncate() : MediaQuery.of(context).size.width.truncate();
          final bannerAd = widget.adManager.bannerAd;
          if (width > 0) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (mounted) {
                final bannerAd = widget.adManager.bannerAd;
                final bool widthChanged = _lastBannerWidthDp != width;
                final bool sizeMismatch = bannerAd == null || bannerAd.size.width != width;
                if ((widthChanged || !_isAdLoaded || sizeMismatch) && !_isLoading) {
                  _lastBannerWidthDp = width;
                  setState(() { _isAdLoaded = false; _isLoading = true; });
                  widget.adManager.loadAdaptiveBannerAd(width, () {
                    if (mounted) {
                      setState(() { _isAdLoaded = true; _isLoading = false; });
                    }
                  });
                }
              }
            });
          }
          if (_isAdLoaded && bannerAd != null) {
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(height: 10),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SizedBox(
                      width: bannerAd.size.width.toDouble(),
                      height: bannerAd.size.height.toDouble(),
                      child: AdWidget(ad: bannerAd),
                    ),
                  ],
                )
              ]
            );
          } else {
            return const SizedBox.shrink();
          }
        },
      ),
    );
  }
}
import 'dart:async';
import 'dart:io' show Platform;
import 'dart:ui';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:flutter/widgets.dart';

import 'package:wheellotterymachine/_secrets.dart';

class AdManager {
  static String get _adUnitId => Platform.isIOS ? Secrets.adUnitIdIos : Secrets.adUnitIdAndroid;
  BannerAd? _bannerAd;
  int _lastWidthPx = 0;
  VoidCallback? _onLoadedCb;
  Timer? _retryTimer;
  int _retryAttempt = 0;

  BannerAd? get bannerAd => _bannerAd;

  /// アプリ起動時の設定
  /// UMP(同意管理)を導入したため、手動のNPA設定は不要になった。
  static Future<void> initForNPA() async {
    if (kIsWeb) {
      return;
    }
    // UMP SDK が保存した同意情報を MobileAds SDK が自動で読み取るため、
    // ここで RequestConfiguration を使って NPA を強制する必要はない。
    await MobileAds.instance.updateRequestConfiguration(
      RequestConfiguration(
        tagForChildDirectedTreatment: TagForChildDirectedTreatment.unspecified,
        testDeviceIds: Secrets.umpConsentTestDeviceIds, //テストデバイスID:広告の誤クリック防止
      ),
    );
  }

  Future<void> loadAdaptiveBannerAd(int widthPx, VoidCallback onAdLoaded) async {
    if (kIsWeb) {
      return;
    }
    _onLoadedCb = onAdLoaded;
    _lastWidthPx = widthPx;
    _retryAttempt = 0;
    _retryTimer?.cancel();
    _startLoad(widthPx);
  }

  static AdRequest getAdRequest() {
    // ユーザーの同意状態(TCF信号)は、SDKによって自動的に付与される。
    // 手動で npa: 1 を送ると、UMPでのユーザーの選択と競合する可能性があるため、空で返す。
    // AdRequest(nonPersonalizedAds: true);にはしない
    return const AdRequest();
  }

  Future<void> _startLoad(int widthPx) async {
    if (kIsWeb) {
      return;
    }
    _bannerAd?.dispose();
    AnchoredAdaptiveBannerAdSize? adaptiveSize;
    try {
      adaptiveSize = await AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(widthPx);
    } catch (_) {
      adaptiveSize = null;
    }
    final AdSize size = adaptiveSize ?? AdSize.fullBanner;
    _bannerAd = BannerAd(
      adUnitId: _adUnitId,
      request: getAdRequest(),
      size: size,
      listener: BannerAdListener(
        onAdLoaded: (ad) {
          _retryTimer?.cancel();
          _retryAttempt = 0;
          final cb = _onLoadedCb;
          if (cb != null) {
            cb();
          }
        },
        onAdFailedToLoad: (ad, err) {
          ad.dispose();
          _scheduleRetry();
        },
      ),
    )..load();
  }

  void _scheduleRetry() {
    if (kIsWeb) return;
    _retryTimer?.cancel();
    _retryAttempt = (_retryAttempt + 1).clamp(1, 5);
    final seconds = _retryAttempt >= 4 ? 30 : (3 << (_retryAttempt - 1));
    _retryTimer = Timer(Duration(seconds: seconds), () {
      _startLoad(_lastWidthPx > 0 ? _lastWidthPx : 320);
    });
  }

  void dispose() {
    _bannerAd?.dispose();
    _retryTimer?.cancel();
  }
}
import 'dart:async';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:flutter/widgets.dart';

import 'package:wheellotterymachine/l10n/app_localizations.dart';
import 'package:wheellotterymachine/_secrets.dart';

/// UMP状態格納用
class AdUmpState {
  final PrivacyOptionsRequirementStatus privacyStatus;
  final ConsentStatus consentStatus;
  final bool privacyOptionsRequired;
  final bool isChecking;
  const AdUmpState({
    required this.privacyStatus,
    required this.consentStatus,
    required this.privacyOptionsRequired,
    required this.isChecking,
  });

  AdUmpState copyWith({
    PrivacyOptionsRequirementStatus? privacyStatus,
    ConsentStatus? consentStatus,
    bool? privacyOptionsRequired,
    bool? isChecking,
  }) {
    return AdUmpState(
      privacyStatus: privacyStatus ?? this.privacyStatus,
      consentStatus: consentStatus ?? this.consentStatus,
      privacyOptionsRequired:
      privacyOptionsRequired ?? this.privacyOptionsRequired,
      isChecking: isChecking ?? this.isChecking,
    );
  }

  static const initial = AdUmpState(
    privacyStatus: PrivacyOptionsRequirementStatus.unknown,
    consentStatus: ConsentStatus.unknown,
    privacyOptionsRequired: false,
    isChecking: false,
  );
}

//UMPコントローラ
class UmpConsentController {
  //デバッグ用:同意フォームの表示テスト:EEA地域を強制する(本番ではfalseにすること)
  final bool forceEeaForDebug = false;
  //デバッグ用:同意フォームの表示テスト:EEA地域を強制するテストデバイスID
  static final List<String> _testDeviceIds = Secrets.umpConsentTestDeviceIds;

  ConsentRequestParameters _buildParams() {
    if (forceEeaForDebug && _testDeviceIds.isNotEmpty) {
      return ConsentRequestParameters(
        consentDebugSettings: ConsentDebugSettings(
          debugGeography: DebugGeography.debugGeographyEea,
          testIdentifiers: _testDeviceIds,
        ),
      );
    }
    return ConsentRequestParameters();
  }

  //同意情報を更新して状態を返す
  Future<AdUmpState> updateConsentInfo({AdUmpState current = AdUmpState.initial}) async {
    if (kIsWeb) {
      return current;
    }
    var state = current.copyWith(isChecking: true);

    try {
      final params = _buildParams();
      final completer = Completer<AdUmpState>();

      ConsentInformation.instance.requestConsentInfoUpdate(
        params,
        () async {
          //同意フォームが必要なら表示する
          ConsentForm.loadAndShowConsentFormIfRequired((formError) async {
            final s = await ConsentInformation.instance.getPrivacyOptionsRequirementStatus();
            final c = await ConsentInformation.instance.getConsentStatus();
            completer.complete(
              state.copyWith(
                privacyStatus: s,
                consentStatus: c,
                privacyOptionsRequired: s == PrivacyOptionsRequirementStatus.required,
                isChecking: false,
              ),
            );
          });
        },
        (FormError e) {
          completer.complete(state.copyWith(isChecking: false));
        },
      );
      return await completer.future;
    } catch (_) {
      return state.copyWith(isChecking: false);
    }
  }

  //プライバシーオプションフォームを表示
  Future<FormError?> showPrivacyOptions() async {
    if (kIsWeb) return null;
    final completer = Completer<FormError?>();
    ConsentForm.showPrivacyOptionsForm((FormError? e) {
      completer.complete(e);
    });
    return completer.future;
  }
}

extension ConsentStatusL10n on ConsentStatus {
  String localized(BuildContext context) {
    final l = AppLocalizations.of(context)!;
    switch (this) {
      case ConsentStatus.obtained:
        return l.cmpConsentStatusObtained;
      case ConsentStatus.required:
        return l.cmpConsentStatusRequired;
      case ConsentStatus.notRequired:
        return l.cmpConsentStatusNotRequired;
      case ConsentStatus.unknown:
        return l.cmpConsentStatusUnknown;
    }
  }
}
import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';

class FramePainter extends CustomPainter {
  final ui.Image frame;
  FramePainter(this.frame);
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    // 1. フレームの短辺を基準に正方形にクロップ
    final side = frame.width < frame.height ? frame.width : frame.height;
    final src = Rect.fromLTWH(
      (frame.width - side) / 2.0,
      (frame.height - side) / 2.0,
      side.toDouble(),
      side.toDouble(),
    );
    // 2. 描画先も正方形に制限
    final length = size.shortestSide;
    final dx = (size.width - length) / 2.0;
    final dy = (size.height - length) / 2.0;
    final dst = Rect.fromLTWH(dx, dy, length, length);
    canvas.drawImageRect(frame, src, dst, paint);
  }
  @override
  bool shouldRepaint(covariant FramePainter oldDelegate) {
    return oldDelegate.frame != frame;
  }
}
import 'dart:async';
import 'dart:math';
import 'dart:ui' as ui;
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:wakelock_plus/wakelock_plus.dart';

import 'package:wheellotterymachine/ad_banner_widget.dart';
import 'package:wheellotterymachine/ad_manager.dart';
import 'package:wheellotterymachine/frame_painter.dart';
import 'package:wheellotterymachine/l10n/app_localizations.dart';
import 'package:wheellotterymachine/pin_prompt.dart';
import 'package:wheellotterymachine/settings_page.dart';
import 'package:wheellotterymachine/text_to_speech.dart';
import 'package:wheellotterymachine/item_state.dart';
import 'package:wheellotterymachine/model.dart';
import 'package:wheellotterymachine/machine_frame_cache.dart';
import 'package:wheellotterymachine/theme_color.dart';
import 'package:wheellotterymachine/main.dart';
import 'package:wheellotterymachine/loading_screen.dart';

class MainHomePage extends StatefulWidget {
  const MainHomePage({super.key});
  @override
  State<MainHomePage> createState() => _HomePageState();
}

class _HomePageState extends State<MainHomePage> with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  late List<ui.Image> _decodedFrames = [];
  final List<String> _balls = const [
    'assets/image/ball_gold.png',
    'assets/image/ball_silver.png',
    'assets/image/ball_purple.png',
    'assets/image/ball_blue.png',
    'assets/image/ball_green.png',
    'assets/image/ball_yellow.png',
    'assets/image/ball_red.png',
    'assets/image/ball_white.png',
  ];
  final Map<int, Offset> _pos = const {
    95: Offset(440, 540),
    96: Offset(457, 558),
    97: Offset(474, 589),
    98: Offset(492, 630),
    99: Offset(508, 620),
    100: Offset(527, 614),
    101: Offset(547, 616),
    102: Offset(567, 627),
    103: Offset(586, 651),
    104: Offset(601, 647),
    105: Offset(617, 650),
    106: Offset(634, 665),
    107: Offset(646, 670),
    108: Offset(657, 680),
    109: Offset(669, 709),
    110: Offset(680, 710),
  };
  late AdManager _adManager;
  final _audio = AudioPlayer();
  late AnimationController _machineAnimationController;
  bool _busy = false;
  int _frame = 0;
  int _choice = 0;
  String _result = '';
  bool _showResult = false;
  late List<ItemState> _items;
  Offset? _lastBallNormPos; // in 900x900 machine coordinates
  //
  late ThemeColor _themeColor;
  bool _isReady = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _initState();
  }

  void _initState() async {
    _adManager = AdManager();
    await TextToSpeech.applyPreferences(Model.ttsVoiceId,Model.ttsVolume);
    _itemsUpdate();
    _machineAnimationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1),
    )
    ..addListener(() {
      final value = _machineAnimationController.value;
      final step = _frameStep();
      final frame = (value * _displayedFrameCount()).floor() * step;
      if (frame != _frame) {
        setState(() {
          _frame = frame;
        });
      }
    })
    ..addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        setState(() {
          _busy = false;
          final lastFrameIndex = _decodedFrames.isEmpty
              ? 119
              : min(119, _decodedFrames.length - 1);
          _frame = lastFrameIndex;
          _showResult = true;
        });
      }
    });
    //
    await _warmMachineFrames();
    _wakelock();
    if (mounted) {
      setState(() {
        _isReady = true;
      });
    }
  }

  void _itemsUpdate() {
    _items = [
      ItemState(name: Model.itemName1, qty: Model.itemQty1),
      ItemState(name: Model.itemName2, qty: Model.itemQty2),
      ItemState(name: Model.itemName3, qty: Model.itemQty3),
      ItemState(name: Model.itemName4, qty: Model.itemQty4),
      ItemState(name: Model.itemName5, qty: Model.itemQty5),
      ItemState(name: Model.itemName6, qty: Model.itemQty6),
      ItemState(name: Model.itemName7, qty: Model.itemQty7),
      ItemState(name: Model.itemName8, qty: Model.itemQty8),
    ];
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _machineAnimationController.dispose();
    _adManager.dispose();
    _audio.dispose();
    TextToSpeech.stop();
    WakelockPlus.disable();
    super.dispose();
  }

  //need with WidgetsBindingObserver
  //WidgetsBinding.instance.addObserver(this);
  //WidgetsBinding.instance.removeObserver(this);
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        _wakelock();
        break;
      case AppLifecycleState.inactive:
      case AppLifecycleState.paused:
      case AppLifecycleState.detached:
      case AppLifecycleState.hidden:
        WakelockPlus.disable();
        break;
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _themeColor = ThemeColor(themeNumber: Model.themeNumber, context: context);
  }

  void _wakelock() {
    if (Model.wakelockEnabled) {
      WakelockPlus.enable();
    } else {
      WakelockPlus.disable();
    }
  }

  Future<void> _speakResult() async {
    if (_result != '' && Model.ttsEnabled && Model.ttsVolume > 0.0) {
      unawaited(TextToSpeech.speak(_result));
    }
  }

  Future<void> _warmMachineFrames() async {
    try {
      final frames = await MachineFrameCache.load();
      if (!mounted) {
        return;
      }
      setState(() {
        _decodedFrames = frames;
      });
    } catch (_) {
    }
  }

  Widget _frameImage(int idx, int targetWidthPx) {
    if (_decodedFrames.isEmpty) {
      return const SizedBox.shrink();
    }
    final safeIndex = idx.clamp(0, _decodedFrames.length - 1).toInt();
    return Center(
      child: SizedBox(
        width: targetWidthPx.toDouble(),
        height: targetWidthPx.toDouble(),
        child: CustomPaint(painter: FramePainter(_decodedFrames[safeIndex])),
      ),
    );
  }

  Future<void> _onStart() async {
    if (_busy) {
      return;
    }
    setState(() {
      _busy = true;
      _result = '';
      _showResult = false;
      _frame = 0;
      _lastBallNormPos = null;
    });
    final sum = _items.fold<int>(0, (p, e) => p + e.qty);
    if (sum == 0) {
      setState(() {
        _result = AppLocalizations.of(context)!.empty;
        _showResult = true;
        _busy = false;
      });
      return;
    }
    final rnd = Random();
    int remain = rnd.nextInt(sum);
    int choice = 0;
    for (int i = 0; i < _items.length; i++) {
      final q = _items[i].qty;
      if (q == 0) {
        continue;
      }
      if (remain >= q) {
        remain -= q;
      } else {
        choice = i; //0|1|2|3|4|5|6|7
        await Model.setQtyResult(choice);  //結果保存
        _itemsUpdate();
        break;
      }
    }
    _choice = choice;
    //機械の音
    if (Model.machineVolume > 0) {
      try {
        await _audio.setSource(AssetSource('sound/garagara2.wav'));
        await _audio.setVolume(Model.machineVolume);
        await _audio.setPlaybackRate((Model.animationQuick + 1).toDouble());
        unawaited(_audio.resume());
      } catch (_) {}
    }
    //機械の回転
    _machineAnimationController
      ..duration = Duration(milliseconds: Model.animationSpeed * _displayedFrameCount())
      ..reset();
    await _machineAnimationController.forward();
    //結果表示
    _result = _items[_choice].name;
    //音声再生
    unawaited(_speakResult());
  }

  int _frameStep() {
    switch (Model.animationQuick) {
      case 1:
        return 2; // 60 frames
      case 2:
        return 3; // 40 frames
      case 3:
        return 4; // 30 frames
      case 4:
        return 6; // 20 frames
      default:
        return 1; // 120 frames
    }
  }

  int _displayedFrameCount() {
    final step = _frameStep();
    return (120 / step).round();
  }

  Future<void> _onSetting() async {
    if (_busy) {
      return;
    }
    if (Model.pin.isNotEmpty) {
      final ok = await PinPrompt.show(context, correctPin: Model.pin);
      if (!ok) {
        return;
      }
    }
    if (!mounted) {
      return;
    }
    final updated = await Navigator.push<bool>(
      context,
      MaterialPageRoute(builder: (_) => const SettingPage()),
    );
    if (mounted && updated == true) {
      MainApp.of(context).rebuildApp();
      await TextToSpeech.applyPreferences(Model.ttsVoiceId,Model.ttsVolume);
      _itemsUpdate();
      _wakelock();
    }
    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return const LoadingScreen();
    }
    return Scaffold(
      backgroundColor: _themeColor.mainBack2Color,
      body: Stack(children:[
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [_themeColor.mainBack2Color, _themeColor.mainBackColor],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
            image: DecorationImage(
              image: AssetImage('assets/image/tile.png'),
              repeat: ImageRepeat.repeat,
              opacity: 0.1,
            ),
          ),
        ),
        SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Row(
                children: [
                  const Spacer(),
                  Padding(
                    padding: const EdgeInsets.only(right: 10),
                    child: IconButton(
                      onPressed: _busy ? null : _onSetting,
                      tooltip: AppLocalizations.of(context)!.setting,
                      icon: Icon(
                        Icons.settings,
                        color: Colors.white.withValues(alpha: 0.85),
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 5),
              Expanded(
                child: LayoutBuilder(
                  builder: (context, c) {
                    final box = min(c.maxWidth, c.maxHeight);
                    final ml = (c.maxWidth - box) / 2;
                    final mt = (c.maxHeight - box) / 2;
                    final bs = box / 25;
                    final op = (_frame >= 95 || _showResult) ? 1.0 : 0.0;
                    Offset? p = _pos[_frame];
                    if (p == null && _frame >= 95) {
                      final keys = _pos.keys.where((k) => k <= _frame).toList()
                        ..sort();
                      if (keys.isNotEmpty) p = _pos[keys.last];
                    }
                    if (p != null) {
                      _lastBallNormPos = p;
                    }
                    // When animation finished, keep showing last position
                    final useP = p ?? (_showResult ? _lastBallNormPos : null);
                    double? x, y;
                    if (useP != null) {
                      final px = box / 900.0;
                      final h = bs / 2;
                      x = ml + px * useP.dx - h;
                      y = mt + px * useP.dy - h;
                    }
                    final idx = _frame.clamp(0, 119).toInt();
                    final dpr = MediaQuery.of(context).devicePixelRatio;
                    final targetWidthPx = max(1, (box * dpr).round());
                    return Stack(
                      children: [
                        _frameImage(idx, targetWidthPx),
                        if (x != null && y != null)
                          Positioned(
                            left: x,
                            top: y,
                            width: bs,
                            height: bs,
                            child: Opacity(
                              opacity: op,
                              child: Image.asset(
                                _balls[_choice],
                                cacheWidth: max(1, (bs * dpr).round()),
                                filterQuality: FilterQuality.low,
                              ),
                            ),
                          ),
                        // Result text at bottom inside the machine area
                        Positioned(
                          left: ml,
                          top: mt,
                          width: box,
                          height: box,
                          child: IgnorePointer(
                            child: AnimatedOpacity(
                              opacity: _showResult ? 1.0 : 0.0,
                              duration: const Duration(milliseconds: 300),
                              child: Align(
                                alignment: Alignment.bottomCenter,
                                child: Padding(
                                  padding: const EdgeInsets.only(bottom: 0),
                                  child: Text(
                                    _result,
                                    textAlign: TextAlign.center,
                                    style: const TextStyle(
                                      color: Colors.white,
                                      fontSize: 24,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    );
                  },
                ),
              ),
              const SizedBox(height: 12),
              Center(
                child: Opacity(
                  opacity: _busy ? 0.4 : 1.0,
                  child: ElevatedButton(
                    onPressed: _busy ? null : _onStart,
                    style: ElevatedButton.styleFrom(
                      shape: const CircleBorder(),
                      fixedSize: const Size(130, 130),
                      backgroundColor: Colors.white.withValues(alpha: 0.25),
                      foregroundColor: Colors.white,
                      elevation: 0,
                    ),
                    child: FittedBox(
                      fit: BoxFit.scaleDown,
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          AppLocalizations.of(context)!.drawLot,
                          textAlign: TextAlign.center,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 48,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        )
      ]),
      bottomNavigationBar: Container(
        decoration: BoxDecoration(color: _themeColor.mainBackColor),
        child: AdBannerWidget(adManager: _adManager),
      ),
    );
  }

}
class ItemState {
  String name;
  int qty;

  ItemState({required this.name, required this.qty});

  ItemState copy() => ItemState(name: name, qty: qty);
}
import 'package:flutter/material.dart';

class LoadingScreen extends StatelessWidget {
  const LoadingScreen({super.key});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromRGBO(61,114,0, 1),
      body: const Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(Colors.lightGreenAccent),
              backgroundColor: Colors.white,
            ),
            SizedBox(height: 16),
            Text(
              'Loading...',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
import 'dart:ui' as ui;
import 'package:flutter/services.dart';

class MachineFrameCache {
  static const int _frameCount = 120;
  static Future<List<ui.Image>>? _pending;
  static List<ui.Image>? _frames;

  static Future<List<ui.Image>> load() {
    final frames = _frames;
    if (frames != null) {
      return Future.value(frames);
    }
    final pending = _pending;
    if (pending != null) {
      return pending;
    }
    final future = _loadFrames();
    _pending = future;
    return future;
  }

  static Future<List<ui.Image>> _loadFrames() async {
    try {
      final decodedFrames = <ui.Image>[];
      for (var i = 0; i < _frameCount; i++) {
        final index = (i + 1).toString().padLeft(3, '0');
        final data = await rootBundle.load('assets/image/machine$index.webp');
        final codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
        final frame = await codec.getNextFrame();
        decodedFrames.add(frame.image);
      }
      _frames = decodedFrames;
      return decodedFrames;
    } finally {
      _pending = null;
    }
  }
}
import 'dart:io';
import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'package:wheellotterymachine/l10n/app_localizations.dart';
import 'package:wheellotterymachine/home_page.dart';
import 'package:wheellotterymachine/model.dart';
import 'package:wheellotterymachine/theme_mode_number.dart';
import 'package:wheellotterymachine/parse_locale_tag.dart';
import 'package:wheellotterymachine/loading_screen.dart';
import 'package:wheellotterymachine/ad_ump_status.dart';
import 'package:wheellotterymachine/ad_manager.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  //ATTを最優先で呼ぶ(広告SDKより前)
  if (!kIsWeb && Platform.isIOS) {
    final status = await AppTrackingTransparency.trackingAuthorizationStatus;
    if (status == TrackingStatus.notDetermined) {
      await Future.delayed(const Duration(milliseconds: 300));
      await AppTrackingTransparency.requestTrackingAuthorization();
    }
  }
  //UI設定
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      systemNavigationBarColor: Colors.transparent,
      statusBarColor: Colors.transparent,
      systemNavigationBarContrastEnforced: false,
      systemStatusBarContrastEnforced: false,
    ),
  );
  runApp(const MainApp());
}

class MainApp extends StatefulWidget {
  const MainApp({super.key});

  static MainAppState of(BuildContext context) {
    return context.findAncestorStateOfType<MainAppState>()!;
  }

  @override
  State<MainApp> createState() => MainAppState();
}

class MainAppState extends State<MainApp> {
  ThemeMode _themeMode = ThemeMode.system;
  Locale? _locale;
  bool _hasError = false;
  bool _isReady = false;

  @override
  void initState() {
    super.initState();
    _initState();
  }

  void _initState() async {
    try {
      //アプリの基本データ
      await Model.ensureReady();
      //UMP(ATTの後)
      final umpController = UmpConsentController();
      await umpController.updateConsentInfo();
      //Mobile Ads SDK(同意確定後)
      await MobileAds.instance.initialize();
      //自前の広告設定
      await AdManager.initForNPA();
      //UI更新
      if (mounted) {
        setState(() {
          _themeMode = ThemeModeNumber.numberToThemeMode(Model.themeNumber);
          _locale = parseLocaleTag(Model.languageCode);
          _isReady = true;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _hasError = true;
        });
      }
    }
  }

  void rebuildApp() {
    setState(() {
      _themeMode = ThemeModeNumber.numberToThemeMode(Model.themeNumber);
      _locale = parseLocaleTag(Model.languageCode);
    });
  }

  Color _getRainbowAccentColor(int hue) {
    return HSVColor.fromAHSV(1.0, hue.toDouble(), 1.0, 1.0).toColor();
  }

  ThemeData _createTheme(Brightness brightness, Color seed) {
    return ThemeData(
      useMaterial3: true,
      colorScheme: ColorScheme.fromSeed(seedColor: seed, brightness: brightness),
      appBarTheme: const AppBarTheme(backgroundColor: Colors.transparent),
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        ),
      ),
      sliderTheme: SliderThemeData(
        showValueIndicator: ShowValueIndicator.onDrag,
        valueIndicatorTextStyle: TextStyle(
          color: brightness == Brightness.light ? Colors.white : Colors.black,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_hasError) {
      return _buildErrorMessage();
    }
    Color seed = _getRainbowAccentColor(Model.schemeColor);
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
      locale: _locale,
      themeMode: _themeMode,
      theme: _createTheme(Brightness.light, seed),
      darkTheme: _createTheme(Brightness.dark, seed),
      home: _isReady ? const MainHomePage() : const Scaffold(body: LoadingScreen()),
    );
  }

  Widget _buildErrorMessage() {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: Padding(
            padding: EdgeInsets.all(24.0),
            child: Text(
              'Initialization failed. Please restart the app.',
              textAlign: TextAlign.center,
            ),
          ),
        ),
      ),
    );
  }

}
import 'dart:ui' as ui;
import 'package:shared_preferences/shared_preferences.dart';

import 'package:wheellotterymachine/l10n/app_localizations.dart';

class Model {
  Model._();

  static const String _prefItemName1 = 'itemName1';
  static const String _prefItemName2 = 'itemName2';
  static const String _prefItemName3 = 'itemName3';
  static const String _prefItemName4 = 'itemName4';
  static const String _prefItemName5 = 'itemName5';
  static const String _prefItemName6 = 'itemName6';
  static const String _prefItemName7 = 'itemName7';
  static const String _prefItemName8 = 'itemName8';
  static const String _prefItemQty1 = 'itemQty1';
  static const String _prefItemQty2 = 'itemQty2';
  static const String _prefItemQty3 = 'itemQty3';
  static const String _prefItemQty4 = 'itemQty4';
  static const String _prefItemQty5 = 'itemQty5';
  static const String _prefItemQty6 = 'itemQty6';
  static const String _prefItemQty7 = 'itemQty7';
  static const String _prefItemQty8 = 'itemQty8';
  static const String _prefPin = 'pin';
  static const String _prefAnimationSpeed = 'animationSpeed';
  static const String _prefAnimationQuick = 'animationQuick';
  static const String _prefMachineVolume = 'machineVolume';
  static const String _prefTtsEnabled = 'ttsEnabled';
  static const String _prefTtsVolume = 'ttsVolume';
  static const String _prefTtsVoiceId = 'ttsVoiceId';
  static const String _prefWakelockEnabled = 'wakelockEnabled';
  static const String _prefSchemeColor = 'schemeColor';
  static const String _prefThemeNumber = 'themeNumber';
  static const String _prefLanguageCode = 'languageCode';

  static bool _ready = false;
  static String _itemName1 = 'Grand Prize';
  static String _itemName2 = 'Second Prize';
  static String _itemName3 = 'Premium Prize';
  static String _itemName4 = 'Prize A';
  static String _itemName5 = 'Prize B';
  static String _itemName6 = 'Prize C';
  static String _itemName7 = 'Consolation Prize';
  static String _itemName8 = 'Thank You Prize';
  static int _itemQty1 = 1;
  static int _itemQty2 = 1;
  static int _itemQty3 = 2;
  static int _itemQty4 = 2;
  static int _itemQty5 = 3;
  static int _itemQty6 = 10;
  static int _itemQty7 = 100;
  static int _itemQty8 = 500;
  static String _pin = '';
  static int _animationSpeed = 25; // 1..1000
  static int _animationQuick = 0; // 0..4
  static double _machineVolume = 1.0; // 0..1
  static bool _ttsEnabled = true;
  static double _ttsVolume = 1.0;
  static String _ttsVoiceId = '';
  static bool _wakelockEnabled = false;
  static int _schemeColor = 120;
  static int _themeNumber = 0;
  static String _languageCode = '';

  static String get itemName1 => _itemName1;
  static String get itemName2 => _itemName2;
  static String get itemName3 => _itemName3;
  static String get itemName4 => _itemName4;
  static String get itemName5 => _itemName5;
  static String get itemName6 => _itemName6;
  static String get itemName7 => _itemName7;
  static String get itemName8 => _itemName8;
  static int get itemQty1 => _itemQty1;
  static int get itemQty2 => _itemQty2;
  static int get itemQty3 => _itemQty3;
  static int get itemQty4 => _itemQty4;
  static int get itemQty5 => _itemQty5;
  static int get itemQty6 => _itemQty6;
  static int get itemQty7 => _itemQty7;
  static int get itemQty8 => _itemQty8;
  static String get pin => _pin;
  static int get animationSpeed => _animationSpeed;
  static bool get ttsEnabled => _ttsEnabled;
  static double get ttsVolume => _ttsVolume;
  static String get ttsVoiceId => _ttsVoiceId;
  static int get animationQuick => _animationQuick;
  static double get machineVolume => _machineVolume;
  static bool get wakelockEnabled => _wakelockEnabled;
  static int get schemeColor => _schemeColor;
  static int get themeNumber => _themeNumber;
  static String get languageCode => _languageCode;

  static Future<void> ensureReady() async {
    if (_ready) {
      return;
    }
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    //
    _itemName1 = prefs.getString(_prefItemName1) ?? '';
    _itemName2 = prefs.getString(_prefItemName2) ?? '';
    _itemName3 = prefs.getString(_prefItemName3) ?? '';
    _itemName4 = prefs.getString(_prefItemName4) ?? '';
    _itemName5 = prefs.getString(_prefItemName5) ?? '';
    _itemName6 = prefs.getString(_prefItemName6) ?? '';
    _itemName7 = prefs.getString(_prefItemName7) ?? '';
    _itemName8 = prefs.getString(_prefItemName8) ?? '';
    _itemQty1 = (prefs.getInt(_prefItemQty1) ?? 0).clamp(0,9999999);
    _itemQty2 = (prefs.getInt(_prefItemQty2) ?? 0).clamp(0,9999999);
    _itemQty3 = (prefs.getInt(_prefItemQty3) ?? 0).clamp(0,9999999);
    _itemQty4 = (prefs.getInt(_prefItemQty4) ?? 0).clamp(0,9999999);
    _itemQty5 = (prefs.getInt(_prefItemQty5) ?? 0).clamp(0,9999999);
    _itemQty6 = (prefs.getInt(_prefItemQty6) ?? 0).clamp(0,9999999);
    _itemQty7 = (prefs.getInt(_prefItemQty7) ?? 0).clamp(0,9999999);
    _itemQty8 = (prefs.getInt(_prefItemQty8) ?? 0).clamp(0,9999999);
    _pin = prefs.getString(_prefPin) ?? '';
    _animationSpeed = (prefs.getInt(_prefAnimationSpeed) ?? 25).clamp(1, 1000);
    _animationQuick = (prefs.getInt(_prefAnimationQuick) ?? 0).clamp(0, 4);
    _machineVolume = (prefs.getDouble(_prefMachineVolume) ?? 1.0).clamp(0.0, 1.0);
    _ttsEnabled = prefs.getBool(_prefTtsEnabled) ?? true;
    _ttsVolume = (prefs.getDouble(_prefTtsVolume) ?? 1.0).clamp(0.0, 1.0);
    _ttsVoiceId = prefs.getString(_prefTtsVoiceId) ?? '';
    _wakelockEnabled = prefs.getBool(_prefWakelockEnabled) ?? false;
    _schemeColor = (prefs.getInt(_prefSchemeColor) ?? 120).clamp(0, 360);
    _themeNumber = (prefs.getInt(_prefThemeNumber) ?? 0).clamp(0, 2);
    _languageCode = prefs.getString(_prefLanguageCode) ?? ui.PlatformDispatcher.instance.locale.languageCode;
    _languageCode = _resolveLanguageCode(_languageCode);
    _setDefaultItems();
    _ready = true;
  }

  static String _resolveLanguageCode(String code) {
    final supported = AppLocalizations.supportedLocales;
    if (supported.any((l) => l.languageCode == code)) {
      return code;
    } else {
      return '';
    }
  }

  static void _setDefaultItems() async {
    if (	_itemName1 == ''
        && _itemName2 == ''
        && _itemName3 == ''
        && _itemName4 == ''
        && _itemName5 == ''
        && _itemName6 == ''
        && _itemName7 == ''
        && _itemName8 == ''
    ) {
      _itemName1 = 'Grand Prize';
      _itemName2 = 'Second Prize';
      _itemName3 = 'Premium Prize';
      _itemName4 = 'Prize A';
      _itemName5 = 'Prize B';
      _itemName6 = 'Prize C';
      _itemName7 = 'Consolation Prize';
      _itemName8 = 'Thank You Prize';
      _itemQty1 = 1;
      _itemQty2 = 1;
      _itemQty3 = 2;
      _itemQty4 = 2;
      _itemQty5 = 3;
      _itemQty6 = 10;
      _itemQty7 = 100;
      _itemQty8 = 500;
      await setItemName1(_itemName1);
      await setItemName2(_itemName2);
      await setItemName3(_itemName3);
      await setItemName4(_itemName4);
      await setItemName5(_itemName5);
      await setItemName6(_itemName6);
      await setItemName7(_itemName7);
      await setItemName8(_itemName8);
      await setItemQty1(_itemQty1);
      await setItemQty2(_itemQty2);
      await setItemQty3(_itemQty3);
      await setItemQty4(_itemQty4);
      await setItemQty5(_itemQty5);
      await setItemQty6(_itemQty6);
      await setItemQty7(_itemQty7);
      await setItemQty8(_itemQty8);
    }
  }

  static Future<void> setQtyResult(int choice) async {
    if (choice == 0) {
      await setItemQty1(_itemQty1 - 1);
    } else if (choice == 1) {
      await setItemQty2(_itemQty2 - 1);
    } else if (choice == 2) {
      await setItemQty3(_itemQty3 - 1);
    } else if (choice == 3) {
      await setItemQty4(_itemQty4 - 1);
    } else if (choice == 4) {
      await setItemQty5(_itemQty5 - 1);
    } else if (choice == 5) {
      await setItemQty6(_itemQty6 - 1);
    } else if (choice == 6) {
      await setItemQty7(_itemQty7 - 1);
    } else if (choice == 7) {
      await setItemQty8(_itemQty8 - 1);
    }
  }

  static Future<void> setItemName1(String value) async {
    _itemName1 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName1, value);
  }

  static Future<void> setItemName2(String value) async {
    _itemName2 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName2, value);
  }

  static Future<void> setItemName3(String value) async {
    _itemName3 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName3, value);
  }

  static Future<void> setItemName4(String value) async {
    _itemName4 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName4, value);
  }

  static Future<void> setItemName5(String value) async {
    _itemName5 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName5, value);
  }

  static Future<void> setItemName6(String value) async {
    _itemName6 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName6, value);
  }

  static Future<void> setItemName7(String value) async {
    _itemName7 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName7, value);
  }

  static Future<void> setItemName8(String value) async {
    _itemName8 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefItemName8, value);
  }

  static Future<void> setItemQty1(int value) async {
    _itemQty1 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty1, value);
  }

  static Future<void> setItemQty2(int value) async {
    _itemQty2 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty2, value);
  }

  static Future<void> setItemQty3(int value) async {
    _itemQty3 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty3, value);
  }

  static Future<void> setItemQty4(int value) async {
    _itemQty4 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty4, value);
  }

  static Future<void> setItemQty5(int value) async {
    _itemQty5 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty5, value);
  }

  static Future<void> setItemQty6(int value) async {
    _itemQty6 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty6, value);
  }

  static Future<void> setItemQty7(int value) async {
    _itemQty7 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty7, value);
  }

  static Future<void> setItemQty8(int value) async {
    _itemQty8 = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefItemQty8, value);
  }

  static Future<void> setPin(String value) async {
    _pin = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefPin, value);
  }

  static Future<void> setAnimationSpeed(int value) async {
    _animationSpeed = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefAnimationSpeed, value);
  }

  static Future<void> setAnimationQuick(int value) async {
    _animationQuick = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefAnimationQuick, value);
  }

  static Future<void> setMachineVolume(double value) async {
    _machineVolume = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setDouble(_prefMachineVolume, value);
  }

  static Future<void> setTtsEnabled(bool value) async {
    _ttsEnabled = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_prefTtsEnabled, value);
  }

  static Future<void> setTtsVolume(double value) async {
    _ttsVolume = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setDouble(_prefTtsVolume, value);
  }

  static Future<void> setTtsVoiceId(String value) async {
    _ttsVoiceId = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefTtsVoiceId, value);
  }

  static Future<void> setWakelockEnabled(bool value) async {
    _wakelockEnabled = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_prefWakelockEnabled, value);
  }

  static Future<void> setSchemeColor(int value) async {
    _schemeColor = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefSchemeColor, value);
  }

  static Future<void> setThemeNumber(int value) async {
    _themeNumber = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefThemeNumber, value);
  }

  static Future<void> setLanguageCode(String value) async {
    _languageCode = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefLanguageCode, value);
  }

}
import 'dart:ui';

Locale? parseLocaleTag(String tag) {
  if (tag.isEmpty) {
    return null;
  }
  final parts = tag.split('-');
  final language = parts[0];
  String? script, country;
  if (parts.length >= 2) {
    parts[1].length == 4 ? script = parts[1] : country = parts[1];
  }
  if (parts.length >= 3) {
    parts[2].length == 4 ? script = parts[2] : country = parts[2];
  }
  return Locale.fromSubtags(
    languageCode: language,
    scriptCode: script,
    countryCode: country,
  );
}
import 'package:flutter/material.dart';

class PinPrompt {
  static Future<bool> show(BuildContext context, {required String correctPin}) async {
    final c = TextEditingController();
    final ok = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('PIN'),
        content: TextField(
          controller: c,
          keyboardType: TextInputType.number,
          obscureText: true,
          decoration: const InputDecoration(hintText: 'Enter PIN'),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('OK'),
          ),
        ],
      ),
    );
    if (ok != true) {
      return false;
    }
    return c.text == correctPin;
  }
}
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:in_app_review/in_app_review.dart';

import 'package:wheellotterymachine/l10n/app_localizations.dart';
import 'package:wheellotterymachine/ad_manager.dart';
import 'package:wheellotterymachine/ad_banner_widget.dart';
import 'package:wheellotterymachine/ad_ump_status.dart';
import 'package:wheellotterymachine/model.dart';
import 'package:wheellotterymachine/text_to_speech.dart';
import 'package:wheellotterymachine/theme_color.dart';
import 'package:wheellotterymachine/loading_screen.dart';
import 'package:wheellotterymachine/_secrets.dart';

class SettingPage extends StatefulWidget {
  const SettingPage({super.key});

  @override
  State<SettingPage> createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  late AdManager _adManager;
  late UmpConsentController _adUmp;
  AdUmpState _adUmpState = AdUmpState.initial;
  bool _wakelockEnabled = false;
  int _themeNumber = 0;
  String _languageCode = '';
  late ThemeColor _themeColor;
  final _inAppReview = InAppReview.instance;
  bool _isReady = false;
  bool _isFirst = true;
  //
  final List<TextEditingController> _nameControls = [
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
  ];
  final List<TextEditingController> _qtyControls = [
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
  ];
  late final TextEditingController _pinControl;
  late final TextEditingController _animationSpeedControl;
  int _animationQuick = 0;
  double _machineVolume = 1.0;
  late List<TtsOption> _ttsVoices;
  bool _ttsEnabled = true;
  double _ttsVolume = 1.0;
  String _ttsVoiceId = '';
  int _schemeColor = 0;
  Color _accentColor = Colors.red;
  //
  final List<String> _ballAssets = const [
    'assets/image/ball_gold.png',
    'assets/image/ball_silver.png',
    'assets/image/ball_purple.png',
    'assets/image/ball_blue.png',
    'assets/image/ball_green.png',
    'assets/image/ball_yellow.png',
    'assets/image/ball_red.png',
    'assets/image/ball_white.png',
  ];
  final List<String> _ballLabels = const [
    'GOLD',
    'SILVER',
    'PURPLE',
    'BLUE',
    'GREEN',
    'YELLOW',
    'RED',
    'WHITE',
  ];

  @override
  void initState() {
    super.initState();
    _initState();
  }

  Future<void> _initState() async {
    _adManager = AdManager();
    _wakelockEnabled = Model.wakelockEnabled;
    _themeNumber = Model.themeNumber;
    _languageCode = Model.languageCode;
    //
    _adUmp = UmpConsentController();
    _refreshConsentInfo();
    //
    _nameControls[0] = TextEditingController(text: Model.itemName1);
    _nameControls[1] = TextEditingController(text: Model.itemName2);
    _nameControls[2] = TextEditingController(text: Model.itemName3);
    _nameControls[3] = TextEditingController(text: Model.itemName4);
    _nameControls[4] = TextEditingController(text: Model.itemName5);
    _nameControls[5] = TextEditingController(text: Model.itemName6);
    _nameControls[6] = TextEditingController(text: Model.itemName7);
    _nameControls[7] = TextEditingController(text: Model.itemName8);
    _qtyControls[0] = TextEditingController(text: Model.itemQty1.toString());
    _qtyControls[1] = TextEditingController(text: Model.itemQty2.toString());
    _qtyControls[2] = TextEditingController(text: Model.itemQty3.toString());
    _qtyControls[3] = TextEditingController(text: Model.itemQty4.toString());
    _qtyControls[4] = TextEditingController(text: Model.itemQty5.toString());
    _qtyControls[5] = TextEditingController(text: Model.itemQty6.toString());
    _qtyControls[6] = TextEditingController(text: Model.itemQty7.toString());
    _qtyControls[7] = TextEditingController(text: Model.itemQty8.toString());
    _pinControl = TextEditingController(text: Model.pin);
    _animationSpeedControl = TextEditingController(text: Model.animationSpeed.toString());
    _animationQuick = Model.animationQuick;
    _machineVolume = Model.machineVolume;
    _ttsEnabled = Model.ttsEnabled;
    _ttsVolume = Model.ttsVolume;
    _ttsVoiceId = Model.ttsVoiceId;
    _schemeColor = Model.schemeColor;
    _accentColor = _getRainbowAccentColor(_schemeColor);
    //speech
    await TextToSpeech.getInstance();
    _ttsVoices = TextToSpeech.ttsVoices;
    //
    setState(() {
      _isReady = true;
    });
  }

  @override
  void dispose() {
    _pinControl.dispose();
    _animationSpeedControl.dispose();
    for (final c in _nameControls) {
      c.dispose();
    }
    for (final c in _qtyControls) {
      c.dispose();
    }
    _adManager.dispose();
    unawaited(TextToSpeech.stop());
    super.dispose();
  }

  Future<void> _refreshConsentInfo() async {
    _adUmpState = await _adUmp.updateConsentInfo(current: _adUmpState);
    if (!mounted) {
      return;
    }
    setState(() {});
  }

  Future<void> _onTapPrivacyOptions() async {
    final err = await _adUmp.showPrivacyOptions();
    await _refreshConsentInfo();
    if (err != null && mounted) {
      final l = AppLocalizations.of(context)!;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('${l.cmpErrorOpeningSettings} ${err.message}')),
      );
    }
  }

  Color _getRainbowAccentColor(int hue) {
    return HSVColor.fromAHSV(1.0, hue.toDouble(), 1.0, 1.0).toColor();
  }

  void _onApply() async {
    await Model.setItemName1(_nameControls[0].text.trim());
    await Model.setItemName2(_nameControls[1].text.trim());
    await Model.setItemName3(_nameControls[2].text.trim());
    await Model.setItemName4(_nameControls[3].text.trim());
    await Model.setItemName5(_nameControls[4].text.trim());
    await Model.setItemName6(_nameControls[5].text.trim());
    await Model.setItemName7(_nameControls[6].text.trim());
    await Model.setItemName8(_nameControls[7].text.trim());
    await Model.setItemQty1(int.tryParse(_qtyControls[0].text.trim()) ?? 0);
    await Model.setItemQty2(int.tryParse(_qtyControls[1].text.trim()) ?? 0);
    await Model.setItemQty3(int.tryParse(_qtyControls[2].text.trim()) ?? 0);
    await Model.setItemQty4(int.tryParse(_qtyControls[3].text.trim()) ?? 0);
    await Model.setItemQty5(int.tryParse(_qtyControls[4].text.trim()) ?? 0);
    await Model.setItemQty6(int.tryParse(_qtyControls[5].text.trim()) ?? 0);
    await Model.setItemQty7(int.tryParse(_qtyControls[6].text.trim()) ?? 0);
    await Model.setItemQty8(int.tryParse(_qtyControls[7].text.trim()) ?? 0);
    await Model.setPin(_pinControl.text.trim());
    await Model.setAnimationSpeed(int.tryParse(_animationSpeedControl.text.trim()) ?? 25);
    await Model.setAnimationQuick(_animationQuick);
    await Model.setMachineVolume(_machineVolume);
    await Model.setTtsEnabled(_ttsEnabled);
    await Model.setTtsVolume(_ttsVolume);
    await Model.setTtsVoiceId(_ttsVoiceId);
    await Model.setWakelockEnabled(_wakelockEnabled);
    await Model.setSchemeColor(_schemeColor);
    await Model.setThemeNumber(_themeNumber);
    await Model.setLanguageCode(_languageCode);
    if (!mounted) {
      return;
    }
    Navigator.of(context).pop(true);
  }

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return const LoadingScreen();
    }
    if (_isFirst) {
      _isFirst = false;
      _themeColor = ThemeColor(themeNumber: _themeNumber, context: context);
    }
    final l = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: _themeColor.backColor,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: const Icon(Icons.close),
          tooltip: l.cancel,
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: null,
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 10),
            child: IconButton(
              onPressed: _onApply,
              tooltip: l.apply,
              icon: const Icon(Icons.check),
            ),
          ),
        ],
      ),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: SafeArea(
          child: Column(
            children: [
              Expanded(
                child: ListView(
                  padding: const EdgeInsets.only(left: 8, right: 8, top: 8, bottom: 100),
                  children: [
                    _buildItemsTable(l),
                    _buildPin(l),
                    _buildAnimationSpeed(l),
                    _buildAnimationQuick(l),
                    _buildMachineVolume(l),
                    _buildSpeech(l),
                    _buildWakelockEnabled(l),
                    _buildSchemeColor(l),
                    _buildTheme(l),
                    _buildLanguage(l),
                    _buildReview(l),
                    _buildCmp(l),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
      bottomNavigationBar: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(height: 10),
          AdBannerWidget(adManager: _adManager),
        ],
      ),
    );
  }

  Widget _buildItemsTable(AppLocalizations l) {
    return Card(
      margin: const EdgeInsets.only(left: 4, top: 0, right: 4, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(l.resultsAndQuantity),
            const SizedBox(height: 8),
            Table(
              columnWidths: const {
                0: FixedColumnWidth(24),
                1: IntrinsicColumnWidth(),
                2: FlexColumnWidth(1),
                3: FixedColumnWidth(64),
              },
              defaultVerticalAlignment: TableCellVerticalAlignment.middle,
              children: List.generate(8, (i) {
                return TableRow(
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(4),
                      child: Image.asset(_ballAssets[i], width: 20, height: 20),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(4),
                      child: Text(_ballLabels[i]),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(4),
                      child: TextField(
                        controller: _nameControls[i],
                        decoration: InputDecoration(
                          isDense: true,
                          hintText: 'Name',
                        ),
                        inputFormatters: [LengthLimitingTextInputFormatter(50)],
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(4),
                      child: SizedBox(
                        width: 60,
                        child: TextField(
                          controller: _qtyControls[i],
                          keyboardType: TextInputType.number,
                          inputFormatters: [
                            FilteringTextInputFormatter.digitsOnly,
                          ],
                          decoration: const InputDecoration(isDense: true),
                        ),
                      ),
                    ),
                  ],
                );
              }),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPin(AppLocalizations l) {
    return Card(
      margin: const EdgeInsets.only(left: 4, top: 12, right: 4, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Text(l.pin),
                const SizedBox(width: 12),
                Expanded(
                  child: TextField(
                    controller: _pinControl,
                    obscureText: true,
                    decoration: const InputDecoration(isDense: true),
                    keyboardType: TextInputType.number,
                    inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 6),
            Text(
              l.pinNote,
              style: const TextStyle(fontSize: 12, color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAnimationSpeed(AppLocalizations l) {
    return Card(
      margin: const EdgeInsets.only(left: 4, top: 12, right: 4, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Text(l.animationSpeed),
                const SizedBox(width: 12),
                Expanded(
                  child: TextField(
                    controller: _animationSpeedControl,
                    keyboardType: TextInputType.number,
                    inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                    decoration: const InputDecoration(isDense: true),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAnimationQuick(AppLocalizations l) {
    return Card(
      margin: const EdgeInsets.only(left: 4, top: 12, right: 4, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(l.animationQuick),
            Row(
              children: <Widget>[
                Text(_animationQuick.toString()),
                Expanded(
                  child: Slider(
                    value: _animationQuick.toDouble(),
                    min: 0,
                    max: 4,
                    divisions: 4,
                    label: _animationQuick.toString(),
                    onChanged: (v) => setState(() => _animationQuick = v.round()),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMachineVolume(AppLocalizations l) {
    return Card(
      margin: const EdgeInsets.only(left: 4, top: 12, right: 4, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(l.machineVolume),
            Row(
              children: <Widget>[
                Text(_machineVolume.toStringAsFixed(1)),
                Expanded(
                  child: Slider(
                    value: _machineVolume,
                    min: 0.0,
                    max: 1.0,
                    divisions: 10,
                    label: _machineVolume.toStringAsFixed(1),
                    onChanged: (v) => setState(() => _machineVolume = v),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSpeech(AppLocalizations l) {
    if (_ttsVoices.isEmpty) {
      return SizedBox.shrink();
    }
    return Column(children:[
      Card(
        margin: const EdgeInsets.only(left: 4, top: 12, right: 4, bottom: 0),
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(12),
            topRight: Radius.circular(12),
            bottomLeft: Radius.circular(0),
            bottomRight: Radius.circular(0),
          ),
        ),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      l.ttsEnabled,
                    ),
                  ),
                  Switch(
                    value: _ttsEnabled,
                    onChanged: (bool value) {
                      setState(() {
                        _ttsEnabled = value;
                      });
                    },
                  ),
                ],
              ),
            ),
          ],
        )
      ),
      Card(
        margin: const EdgeInsets.only(left: 4, top: 2, right: 4, bottom: 0),
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(0),
            topRight: Radius.circular(0),
            bottomLeft: Radius.circular(0),
            bottomRight: Radius.circular(0),
          ),
        ),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(left: 16, right: 16, top: 12),
              child: Row(
                children: [
                  Text(
                    l.ttsVolume,
                  ),
                  const Spacer(),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(left: 16, right: 16),
              child: Row(
                children: <Widget>[
                  Text(_ttsVolume.toStringAsFixed(1)),
                  Expanded(
                    child: Slider(
                      value: _ttsVolume,
                      min: 0.0,
                      max: 1.0,
                      divisions: 10,
                      label: _ttsVolume.toStringAsFixed(1),
                      onChanged: _ttsEnabled
                          ? (double value) {
                        setState(() {
                          _ttsVolume = double.parse(
                            value.toStringAsFixed(1),
                          );
                        });
                      }
                          : null,
                    ),
                  ),
                ],
              ),
            ),
          ],
        )
      ),
      Card(
        margin: const EdgeInsets.only(left: 4, top: 2, right: 4, bottom: 0),
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(0),
            topRight: Radius.circular(0),
            bottomLeft: Radius.circular(12),
            bottomRight: Radius.circular(12),
          ),
        ),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(left: 16, right: 16, top: 4, bottom: 16),
              child: DropdownButtonFormField<String>(
                initialValue: () {
                  if (_ttsVoiceId.isNotEmpty && _ttsVoices.any((o) => o.id == _ttsVoiceId)) {
                    return _ttsVoiceId;
                  }
                  return _ttsVoices.first.id;
                }(),
                items: _ttsVoices
                    .map((o) => DropdownMenuItem<String>(value: o.id, child: Text(o.label)))
                    .toList(),
                onChanged: (v) {
                  if (v == null) {
                    return;
                  }
                  setState(() => _ttsVoiceId = v);
                },
              ),
            ),
          ],
        )
      )
    ]);
  }

  Widget _buildWakelockEnabled(AppLocalizations l) {
    final TextTheme t = Theme.of(context).textTheme;
    return Card(
      margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
        child: Row(
          children: [
            Expanded(
              child: Text(
                l.wakelockEnabled,
                style: t.bodyMedium,
              ),
            ),
            Switch(
              value: _wakelockEnabled,
              onChanged: (value) {
                setState(() {
                  _wakelockEnabled = value;
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSchemeColor(AppLocalizations l) {
    return Card(
        margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(left: 16, right: 16, top: 16),
              child: Row(
                children: [
                  Text(l.colorScheme),
                  const Spacer(),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(left: 16, right: 16),
              child: Row(
                children: <Widget>[
                  Text(_schemeColor.toStringAsFixed(0)),
                  Expanded(
                      child: SliderTheme(
                          data: SliderTheme.of(context).copyWith(
                            activeTrackColor: _accentColor,
                            inactiveTrackColor: _accentColor.withValues(alpha: 0.3),
                            thumbColor: _accentColor,
                            overlayColor: _accentColor.withValues(alpha: 0.2),
                            valueIndicatorColor: _accentColor,
                          ),
                          child: Slider(
                              value: _schemeColor.toDouble(),
                              min: 0,
                              max: 360,
                              divisions: 360,
                              label: _schemeColor.toString(),
                              onChanged: (double value) {
                                setState(() {
                                  _schemeColor = value.toInt();
                                  _accentColor = _getRainbowAccentColor(_schemeColor);
                                });
                              }
                          )
                      )
                  ),
                ],
              ),
            ),
          ],
        )
    );
  }

  Widget _buildTheme(AppLocalizations l) {
    final TextTheme t = Theme.of(context).textTheme;
    return Card(
      margin: const EdgeInsets.only(left: 4, top: 12, right: 4, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
        child: Row(
          children: [
            Expanded(
              child: Text(
                l.theme,
                style: t.bodyMedium,
              ),
            ),
            DropdownButton<int>(
              value: _themeNumber,
              items: [
                DropdownMenuItem(value: 0, child: Text(l.systemSetting)),
                DropdownMenuItem(value: 1, child: Text(l.lightTheme)),
                DropdownMenuItem(value: 2, child: Text(l.darkTheme)),
              ],
              onChanged: (value) {
                if (value != null) {
                  setState(() {
                    _themeNumber = value;
                  });
                }
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLanguage(AppLocalizations l) {
    final Map<String,String> languageNames = {
      'af': 'af: Afrikaans',
      'ar': 'ar: العربية',
      'bg': 'bg: Български',
      'bn': 'bn: বাংলা',
      'bs': 'bs: Bosanski',
      'ca': 'ca: Català',
      'cs': 'cs: Čeština',
      'da': 'da: Dansk',
      'de': 'de: Deutsch',
      'el': 'el: Ελληνικά',
      'en': 'en: English',
      'es': 'es: Español',
      'et': 'et: Eesti',
      'fa': 'fa: فارسی',
      'fi': 'fi: Suomi',
      'fil': 'fil: Filipino',
      'fr': 'fr: Français',
      'gu': 'gu: ગુજરાતી',
      'he': 'he: עברית',
      'hi': 'hi: हिन्दी',
      'hr': 'hr: Hrvatski',
      'hu': 'hu: Magyar',
      'id': 'id: Bahasa Indonesia',
      'it': 'it: Italiano',
      'ja': 'ja: 日本語',
      //'jv': 'jv: Basa Jawa',    //flutterのサポート外
      'km': 'km: ខ្មែរ',
      'kn': 'kn: ಕನ್ನಡ',
      'ko': 'ko: 한국어',
      'lt': 'lt: Lietuvių',
      'lv': 'lv: Latviešu',
      'ml': 'ml: മലയാളം',
      'mr': 'mr: मराठी',
      'ms': 'ms: Bahasa Melayu',
      'my': 'my: မြန်မာ',
      'ne': 'ne: नेपाली',
      'nl': 'nl: Nederlands',
      'or': 'or: ଓଡ଼ିଆ',
      'pa': 'pa: ਪੰਜਾਬੀ',
      'pl': 'pl: Polski',
      'pt': 'pt: Português',
      'ro': 'ro: Română',
      'ru': 'ru: Русский',
      'si': 'si: සිංහල',
      'sk': 'sk: Slovenčina',
      'sr': 'sr: Српски',
      'sv': 'sv: Svenska',
      'sw': 'sw: Kiswahili',
      'ta': 'ta: தமிழ்',
      'te': 'te: తెలుగు',
      'th': 'th: ไทย',
      'tl': 'tl: Tagalog',
      'tr': 'tr: Türkçe',
      'uk': 'uk: Українська',
      'ur': 'ur: اردو',
      'uz': 'uz: Oʻzbekcha',
      'vi': 'vi: Tiếng Việt',
      'zh': 'zh: 中文',
      'zu': 'zu: isiZulu',
    };
    final TextTheme t = Theme.of(context).textTheme;
    return Card(
      margin: const EdgeInsets.only(left: 4, top: 12, right: 4, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
        child: Row(
          children: [
            Expanded(
              child: Text(
                l.language,
                style: t.bodyMedium,
              ),
            ),
            DropdownButton<String?>(
              value: _languageCode,
              items: [
                DropdownMenuItem(value: '', child: Text('Default')),
                ...languageNames.entries.map((entry) => DropdownMenuItem<String?>(
                  value: entry.key,
                  child: Text(entry.value),
                )),
              ],
              onChanged: (String? value) {
                setState(() {
                  _languageCode = value ?? '';
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildReview(AppLocalizations l) {
    final TextTheme t = Theme.of(context).textTheme;
    return Card(
      margin: const EdgeInsets.only(left: 0, top: 12, right: 0, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(l.reviewApp, style: t.bodyMedium),
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                OutlinedButton.icon(
                  icon: Icon(Icons.open_in_new, size: 16),
                  label: Text(l.reviewStore, style: t.bodySmall),
                  style: OutlinedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 1, horizontal: 12),
                    side: BorderSide(color: Theme.of(context).colorScheme.primary),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  onPressed: () async {
                    await _inAppReview.openStoreListing(
                      appStoreId: Secrets.appStoreId,
                    );
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCmp(AppLocalizations l) {
    String statusLabel;
    IconData statusIcon;
    final showButton =
        _adUmpState.privacyStatus == PrivacyOptionsRequirementStatus.required;
    statusLabel = l.cmpCheckingRegion;
    statusIcon = Icons.help_outline;
    switch (_adUmpState.privacyStatus) {
      case PrivacyOptionsRequirementStatus.required:
        statusLabel = l.cmpRegionRequiresSettings;
        statusIcon = Icons.privacy_tip;
        break;
      case PrivacyOptionsRequirementStatus.notRequired:
        statusLabel = l.cmpRegionNoSettingsRequired;
        statusIcon = Icons.check_circle_outline;
        break;
      case PrivacyOptionsRequirementStatus.unknown:
        statusLabel = l.cmpRegionCheckFailed;
        statusIcon = Icons.error_outline;
        break;
    }
    return Card(
      margin: const EdgeInsets.only(left: 4, top: 12, right: 4, bottom: 0),
      color: _themeColor.cardColor,
      elevation: 0,
      shadowColor: Colors.transparent,
      surfaceTintColor: Colors.transparent,
      child: Padding(
        padding:
        const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 22),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(l.cmpSettingsTitle,
                style: Theme.of(context).textTheme.bodyMedium),
            const SizedBox(height: 8),
            Text(l.cmpConsentDescription,
                style: Theme.of(context).textTheme.bodySmall),
            const SizedBox(height: 8),
            Center(
              child: Column(
                children: [
                  Chip(
                    avatar: Icon(statusIcon, size: 18),
                    label: Text(statusLabel),
                    side: BorderSide.none,
                  ),
                  const SizedBox(height: 4),
                  Text(
                    '${l.cmpConsentStatusLabel} ${_adUmpState.consentStatus.localized(context)}',
                    style: Theme.of(context).textTheme.bodySmall,
                  ),
                  if (showButton)
                    Column(children: [
                      const SizedBox(height: 16),
                      ElevatedButton.icon(
                        onPressed: _adUmpState.isChecking
                            ? null
                            : _onTapPrivacyOptions,
                        icon: const Icon(Icons.settings),
                        label: Text(_adUmpState.isChecking
                            ? l.cmpConsentStatusChecking
                            : l.cmpOpenConsentSettings),
                        style: ElevatedButton.styleFrom(
                          elevation: 0,
                          side: BorderSide(
                            width: 1,
                          ),
                        ),
                      ),
                      const SizedBox(height: 16),
                      OutlinedButton.icon(
                        onPressed:
                        _adUmpState.isChecking ? null : _refreshConsentInfo,
                        icon: const Icon(Icons.refresh),
                        label: Text(l.cmpRefreshStatus),
                      ),
                      const SizedBox(height: 16),
                      OutlinedButton.icon(
                        onPressed: () async {
                          await ConsentInformation.instance.reset();
                          await _refreshConsentInfo();
                          if (mounted) {
                            ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(content: Text(l.cmpResetStatusDone)));
                          }
                        },
                        icon: const Icon(Icons.refresh),
                        label: Text(l.cmpResetStatus),
                      ),
                    ])
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

}
/*
void _initState() async {
  await TextToSpeech.applyPreferences(Model.ttsVoiceId,Model.ttsVolume);
}
@override
void dispose() {
  TextToSpeech.stop();
  super.dispose();
}

void any() {
  await TextToSpeech.speak(text);
}

void _onClickSetting() async {
  final updatedSettings = await Navigator.push(
    context,MaterialPageRoute(builder: (context) => SettingPage()),
  );
  if (updatedSettings != null) {
    await TextToSpeech.applyPreferences(Model.ttsVoiceId,Model.ttsVolume);
  }
}
*/

import 'package:flutter_tts/flutter_tts.dart';
import 'dart:io' show Platform;
import 'package:collection/collection.dart';

class TtsOption {
  final String locale;
  final String name;
  const TtsOption(this.locale, this.name);
  String get id => '$locale|$name';
  String get label => '$locale $name';
}

class TextToSpeech {
  static late FlutterTts _tts;
  static final List<TtsOption> ttsVoices = [];
  static String ttsVoiceId = '';

  static TextToSpeech? _instance;
  static bool _initialized = false;

  TextToSpeech._internal();

  static Future<TextToSpeech> getInstance() async {
    _instance ??= TextToSpeech._internal();
    if (!_initialized) {
      await _instance!._initial();
      _initialized = true;
    }
    return _instance!;
  }

  //声リスト作成
  Future<void> _initial() async {
    _tts = FlutterTts();
    try {
      List<dynamic>? vs;
      for (int i = 0; i < 10; i++) {
        vs = await _tts.getVoices;
        if (vs != null) {
          break;
        }
        await Future.delayed(Duration(seconds: 1));
      }
      if (vs is List) {
        ttsVoices.clear();
        for (final v in vs) {
          if (v is Map && v['name'] is String && v['locale'] is String) {
            ttsVoices.add(TtsOption(v['locale']!, v['name']!));
          }
        }
      }
      ttsVoices.sort((a, b) => a.label.compareTo(b.label));
      ttsVoices.insert(0, TtsOption("Default", ""));
      ttsVoiceId = ttsVoices.first.id;
      await _tts.awaitSpeakCompletion(true);
    } catch (_) {}
  }

  //ttsVoiceIdを登録
  static Future<void> setTtsVoiceId(String newTtsVoiceId) async {
    final exists = ttsVoices.any((o) => o.id == newTtsVoiceId);
    if (exists) {
      ttsVoiceId = newTtsVoiceId;
    } else {
      ttsVoiceId = ttsVoices.first.id;
    }
    await _setSpeechVoiceFromId();
  }

  //ttsVoiceIdの声を用意
  static Future<void> _setSpeechVoiceFromId() async {
    if (ttsVoices.isEmpty || ttsVoiceId.isEmpty) {
      return;
    }
    final idx = ttsVoiceId.indexOf('|');
    String selLocale = '';
    String selName = ttsVoiceId;
    if (idx >= 0) {
      selLocale = ttsVoiceId.substring(0, idx);
      selName = ttsVoiceId.substring(idx + 1);
    }
    TtsOption? match;
    if (selLocale.isNotEmpty) {
      match = ttsVoices.firstWhereOrNull(
            (e) => e.name == selName && e.locale == selLocale,
      );
    }
    match ??= ttsVoices.firstWhereOrNull((e) => e.name == selName);
    if (match != null) {
      final locale = match.locale;
      final name = match.name;
      try {
        if (Platform.isAndroid) {
          // Prefer Google TTS if available; ignore errors if not installed
          try {
            await _tts.setEngine('com.google.android.tts');
          } catch (_) {}
          if (locale.isNotEmpty) {
            await _tts.setLanguage(locale);
          }
          await _tts.setVoice({'name': name, 'locale': locale});
        } else if (Platform.isIOS) {
          // On iOS, setting voice is sufficient; avoid setLanguage overriding the voice
          await _tts.setVoice({'name': name, 'locale': locale});
        } else {
          // Fallback for other platforms
          if (locale.isNotEmpty) {
            await _tts.setLanguage(locale);
          }
          await _tts.setVoice({'name': name, 'locale': locale});
        }
      } catch (_) {}
    }
  }

  //外部から呼び出し。インスタンス生成と設定を同時に行う。
  static Future<void> applyPreferences(String ttsVoiceId, double ttsVolume) async {
    await TextToSpeech.getInstance();
    await TextToSpeech.setTtsVoiceId(ttsVoiceId);
    await TextToSpeech.setVolume(ttsVolume);
  }

  //文字列を音声再生
  static Future<void> speak(String text) async {
    try {
      await _tts.stop();
      await _tts.speak(text);
    } catch (_) {}
  }

  //音声再生を停止
  static Future<void> stop() async {
    try {
      await _tts.stop();
    } catch (_) {}
  }

  //音声再生の速度
  static Future<void> setVolume(double volume) async {
    try {
      await _tts.setVolume(volume);
    } catch (_) {}
  }

  //音声の高さ
  static Future<void> setPitch(double pitch) async {
    try {
      await _tts.setPitch(pitch);
    } catch (_) {}
  }

  //音声の速度
  static Future<void> setSpeechRate(double speechRate) async {
    try {
      await _tts.setSpeechRate(speechRate);
    } catch (_) {}
  }

}
import 'package:flutter/material.dart';

import 'package:wheellotterymachine/model.dart';

class ThemeColor {
  final int? themeNumber;
  final BuildContext context;

  ThemeColor({this.themeNumber, required this.context});

  Brightness get _effectiveBrightness {
    switch (themeNumber) {
      case 1:
        return Brightness.light;
      case 2:
        return Brightness.dark;
      default:
        return Theme.of(context).brightness;
    }
  }

  Color _getRainbowAccentColor(int hue, double saturation, double value) {
    return HSVColor.fromAHSV(1.0, hue.toDouble(), saturation, value).toColor();
  }

  bool get _isLight => _effectiveBrightness == Brightness.light;

  //main page
  Color get mainBackColor => _isLight ? _getRainbowAccentColor(Model.schemeColor,1,0.4) : _getRainbowAccentColor(Model.schemeColor,1,0.1);
  Color get mainBack2Color => _isLight ? _getRainbowAccentColor(Model.schemeColor,1,0.8) : _getRainbowAccentColor(Model.schemeColor,1,0.4);
  Color get mainForeColor => _isLight ? Color.fromRGBO(255, 255, 255, 1.0) : Color.fromRGBO(255, 255, 255, 1.0);
  //setting page
  Color get backColor => _isLight ? Colors.grey[200]! : Colors.grey[900]!;
  Color get cardColor => _isLight ? Colors.white : Colors.grey[800]!;
  Color get appBarForegroundColor => _isLight ? Colors.grey[700]! : Colors.white70;
  Color get dropdownColor => cardColor;
  Color get borderColor => _isLight ? Colors.grey[300]! : Colors.grey[700]!;
  Color get inputFillColor => _isLight ? Colors.grey[50]! : Colors.grey[900]!;
}
import 'package:flutter/material.dart';

class ThemeModeNumber {
  static ThemeMode numberToThemeMode(int value) {
    switch (value) {
      case 1:
        return ThemeMode.light;
      case 2:
        return ThemeMode.dark;
      default:
        return ThemeMode.system;
    }
  }
}