ソースコード source code

下記アプリの主要なソースコードを公開しています。アプリ開発の参考になれば幸いです。

画像等が別途必要ですので下記情報のみでアプリが完成するものではありません。 アプリは少しずつ機能拡張していますのでストア公開されているアプリと内容が異なる場合があります。 コードはコピーして自由にお使いいただけます。ただし著作権は放棄しておりませんので全部の再掲載はご遠慮ください。部分的に再掲載したり、改変して再掲載するのは構いません。 自身のアプリ作成の参考として個人使用・商用問わず自由にお使いいただけます。 コード記述のお手本を示すものではありません。ミニアプリですので変数名などさほど気遣いしていない部分も有りますし間違いも有るかと思いますので参考程度にお考え下さい。 他の賢者の皆様が公開されているコードを参考にした箇所も含まれます。Flutter開発の熟練者が書いたコードではありません。 エンジニア向け技術情報共有サービスではありませんので説明は省いています。 GitHubなどへの公開は予定しておりません。

下記コードの最終ビルド日: 2025-10-19

name: bingoonline
description: "bingoonline"
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.2.2+15

environment:
  sdk: ^3.9.2

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  package_info_plus: ^9.0.0
  shared_preferences: ^2.0.17
  video_player: ^2.5.1
  flutter_svg: ^2.0.10+1
  http: ^1.0.0
  flutter_localizations:     # flutter gen-l10n
    sdk: flutter
  intl: ^0.20.2
  flutter_tts: ^4.0.2
  google_mobile_ads: ^6.0.0
  audioplayers: ^6.5.1


dev_dependencies:
  flutter_test:
    sdk: flutter

  flutter_launcher_icons: ^0.14.4    #flutter pub run flutter_launcher_icons
  flutter_native_splash: ^2.3.2     #flutter pub run flutter_native_splash:create

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^6.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

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: '#3DF99D'
  image: 'assets/image/splash.png'
  color_dark: '#3DF99D'
  image_dark: 'assets/image/splash.png'
  fullscreen: true
  android_12:
    icon_background_color: '#3DF99D'
    image: 'assets/image/splash.png'
    icon_background_color_dark: '#3DF99D'
    image_dark: 'assets/image/splash.png'

# The following section is specific to Flutter packages.
flutter:
  generate: true

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

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

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/to/resolution-aware-images

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/to/asset-from-package

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/to/font-from-package
import 'package:flutter/cupertino.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'package:bingoonline/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();
          }
        },
      ),
    );
  }
}
/*
 *	mainへの記述
 *	void main() async {
 *		WidgetsFlutterBinding.ensureInitialized();
 *		if (!kIsWeb) {
 *			//AdMob初期化
 *			MobileAds.instance.initialize();
 *			//NPAポリシーの集中設定(将来拡張もここで) 現時点は使用していないので記述しなくても良い
 *			await AdManager.initForNPA();
 *		}
 *		runApp(const MyApp());
 *	}
 */

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';

class AdManager {
  //Test IDs
  //static const String _androidAdUnitId = "ca-app-pub-3940256099942544/6300978111";
  //static const String _iosAdUnitId     = "ca-app-pub-3940256099942544/2934735716";

  //Production IDs
  static const String _androidAdUnitId = "ca-app-pub-0/0";
  static const String _iosAdUnitId     = "ca-app-pub-0/0";

  static String get _adUnitId => Platform.isIOS ? _iosAdUnitId : _androidAdUnitId;

  BannerAd? _bannerAd;
  int _lastWidthPx = 0;
  VoidCallback? _onLoadedCb;
  Timer? _retryTimer;
  int _retryAttempt = 0;

  BannerAd? get bannerAd => _bannerAd;

  //(任意)アプリ起動時などに呼ぶ。将来のCMP/NPA関連設定を集中管理。
  static Future<void> initForNPA() async {
    if (kIsWeb) {
      return;
    }
    //ここでグローバルなRequestConfigurationを設定しておく(必要に応じて拡張)
    await MobileAds.instance.updateRequestConfiguration(
      RequestConfiguration(
        //例:最大コンテンツレーティング等を付けたい場合はここに追加
        //maxAdContentRating: MaxAdContentRating.g,	//例
        //tagForChildDirectedTreatment: TagForChildDirectedTreatment.unspecified,
        //tagForUnderAgeOfConsent: TagForUnderAgeOfConsent.unspecified,
      ),
    );
  }

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

  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;

    //常にNPAで配信(CMP対応)
    const adRequest = AdRequest(
      nonPersonalizedAds: true,	//NPA Non-Personalized Ads(非パーソナライズ広告)指定
    );

    _bannerAd = BannerAd(
      adUnitId: _adUnitId,
      request: adRequest,
      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();
    // Exponential backoff: 3s, 6s, 12s, max 30s
    _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();
  }
}

/*
広告配信について
本アプリでは、Google AdMob を利用して広告を表示しています。
当アプリの広告はすべて「非パーソナライズ広告(NPA)」として配信しており、ユーザーの行動履歴や個人情報をもとにしたパーソナライズは一切行っていません。
Google AdMob によって、広告の表示のために以下の情報が利用される場合があります:
- 端末情報(例:OSの種類、画面サイズなど)
- おおまかな位置情報(国・地域レベル)
これらの情報は、パーソナライズを目的としたトラッキングやプロファイリングには使用されません。
詳しくは、Google のプライバシーポリシーをご覧ください:
https://policies.google.com/privacy


Advertising
This app uses Google AdMob to display advertisements.
All ads in this app are served as non-personalized ads (NPA).
This means that we do not use personal data or user behavior information to personalize the ads you see.
Google AdMob may use certain information in order to display ads properly, such as:
- Device information (e.g., OS type, screen size)
- Approximate location information (country/region level)
This information is not used for tracking or profiling for advertising purposes.
For more details, please refer to Google Privacy Policy:
https://policies.google.com/privacy
*/
/*
  CMP(Consent Management Platform)「同意管理プラットフォーム」
  UMP とは、Google AdMobでGDPRの同意を取得するために使用されるライブラリ User Messaging Platform (UMP) SDK

  ad_manager.dart で NPA Non-Personalized Ads(非パーソナライズ広告)指定 している。

  必要な変数
  late final UmpConsentController _adUmp;
  AdUmpState _adUmpState = AdUmpState.initial;

  @override
  void initState() {
    super.initState();
    _adUmp = UmpConsentController();
    _refreshConsentInfo();
  }

  必要な関数
  Future<void> _refreshConsentInfo() async {
    _adUmpState = await _adUmp.updateConsentInfo(current: _adUmpState);
    if (mounted) {
      setState(() {});
    }
  }
  Future<void> _onTapPrivacyOptions() async {
    final err = await _adUmp.showPrivacyOptions();
    await _refreshConsentInfo();
    if (err != null && mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('プライバシー設定画面を表示できませんでした: ${err.message}')),
      );
    }
  }
 */

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:bingoonline/l10n/app_localizations.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;
  //埋め込みのテストデバイスID
  static const List<String> _testDeviceIds = [
    '608970392F100B87D62A1174996C952C', //arrows We2 (M07)
  ];

  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 {
          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(
              privacyStatus: PrivacyOptionsRequirementStatus.unknown,
              consentStatus: ConsentStatus.unknown,
              privacyOptionsRequired: false,
              isChecking: false,
            ),
          );
        },
      );

      state = await completer.future;
      return state;
    } 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;
    }
  }
}
///
/// @author akira ohmachi
/// @copyright ao-system, Inc.
/// @date 2023-01-27
///
library;

class CardCell {
  int number = 0;
  int open = 0;
  CardCell(this.number, this.open); //constructor
  int getNumber() {
    return number;
  }
  int getOpen() {
    return open;
  }
  void setNumber(int number) {
    this.number = number;
  }
  void setOpen(int open) {
    this.open = open;
  }
}
///
/// @author akira ohmachi
/// @copyright ao-system, Inc.
/// @date 2023-01-27
///
library;

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

import 'package:bingoonline/l10n/app_localizations.dart';
import 'package:bingoonline/model.dart';
import 'package:bingoonline/card_page.dart';
import 'package:bingoonline/card_offline.dart';
import 'package:bingoonline/ad_manager.dart';
import 'package:bingoonline/ad_banner_widget.dart';
import 'package:bingoonline/theme_color.dart';


class CardInitPage extends StatefulWidget {
  const CardInitPage({super.key});
  @override
  State<CardInitPage> createState() => _CardInitPageState();
}
class _CardInitPageState extends State<CardInitPage> {
  late AdManager _adManager;
  bool _onlineButtonDisable = false;
  String _message = '';
  String _messageConnectionCodeCard = '';
  int _inputNumber = 0;
  late ThemeColor _themeColor;
  bool _isFirst = true;

  @override
  void initState() {
    super.initState();
    _adManager = AdManager();
    Model.cardIsInitialToNew();
    Model.setConnectionCodeCardWatchFlag(false);
  }

  @override
  void dispose() {
    _adManager.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isFirst) {
      _isFirst = false;
      _themeColor = ThemeColor(themeNumber: Model.themeNumber, context: context);
    }
    final l = AppLocalizations.of(context)!;
    final int number = Model.connectionCodeCard;
    _messageConnectionCodeCard = '${l.currentConnectionCode}: ${number == 0 ? l.none : number.toString()}';
    return Theme(
      data: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.orange,
          brightness: _themeColor.isLight ? Brightness.light : Brightness.dark,
        ),
        useMaterial3: true,
      ),
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          elevation: 0,
          title: Text(l.cardSetting, style: TextStyle(color: _themeColor.cardInitColor)),
        ),
        body: SafeArea(
          top: false,
          left: false,
          right: false,
          bottom: true,
          child: Column(children:[
            Expanded(
              child: GestureDetector(
                onTap: () => FocusScope.of(context).unfocus(),  //背景タップでキーボードを仕舞う
                child: SingleChildScrollView(
                  child: Padding(
                    padding: const EdgeInsets.only(top: 0, left: 12, right: 12, bottom: 100),
                    child: Column(
                      children: [
                        _buildSection1(l),
                        _buildSection2(l),
                        _buildSection3(l),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ]),
        ),
        bottomNavigationBar: AdBannerWidget(adManager: _adManager),
      )
    );
  }

  Widget _buildSection1(AppLocalizations l) {
    return SizedBox(
      width: double.infinity,
      child: Card(
        margin: const EdgeInsets.only(top: 12),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Padding(
          padding: const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 16),
          child: Column(
            children: [
              SizedBox(
                child: Text(l.enterTheConnectionCodeIssuedByTheOrganizerToJoinTheGame,
                  style: Theme.of(context).textTheme.bodySmall,
                  textAlign: TextAlign.left,
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 16),
                child: SizedBox(
                  child: Text(l.connectionCode6DigitNumber,
                    style: Theme.of(context).textTheme.bodySmall,
                    textAlign: TextAlign.center,
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 1, left: 60, right: 60),
                child: TextField(
                  textAlign: TextAlign.center,
                  keyboardType: TextInputType.number, //数字のキーボード
                  inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                  //初期値を設定する場合 controller: TextEditingController(text: 'aaa'),
                  decoration: const InputDecoration(hintText: '000000',
                    hintStyle: TextStyle(color: Colors.black26)
                  ),
                  style: const TextStyle(fontSize: 30),
                  onChanged: (text) {
                    _inputNumber = int.tryParse(text) ?? 0;
                  },
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 16),
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children:[
                      _onlineGame(l),
                      const SizedBox(height:20),
                      _offlineGame(l),
                    ]
                )
              ),
              Padding(
                padding: const EdgeInsets.only(top: 16),
                child: SizedBox(
                  child: Text(_message,
                    style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Colors.redAccent),
                    textAlign: TextAlign.center,
                  ),
                ),
              ),
            ]
          )
        )
      )
    );
  }

  Widget _buildSection2(AppLocalizations l) {
    return SizedBox(
      width: double.infinity,
      child: Card(
        margin: const EdgeInsets.only(top: 12),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Padding(
          padding: const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 16),
          child: Column(
            children: [
              SizedBox(
                child: Text(l.replaceWithANewCard,
                  style: Theme.of(context).textTheme.bodySmall,
                  textAlign: TextAlign.left,
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 4),
                child: _newCard(l),
              ),
            ]
          )
        )
      )
    );
  }

  Widget _buildSection3(AppLocalizations l) {
    return SizedBox(
      width: double.infinity,
      child: Card(
        margin: const EdgeInsets.only(top: 12),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Padding(
          padding: const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 16),
          child: Column(
            children: [
              SizedBox(
                child: Text(_messageConnectionCodeCard,
                  style: Theme.of(context).textTheme.bodySmall?.copyWith(color: _themeColor.cardInitColor),
                  textAlign: TextAlign.center,
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 4),
                child: _cardPage(l),
              ),
            ]
          )
        )
      )
    );
  }

  Widget _onlineGame(AppLocalizations l) {
    return OutlinedButton.icon(
      onPressed: _onlineButtonDisable ? null : () {
        _onlineButtonDisable = true;
        _connectionCodeCardJoin(l);
      },
      style: OutlinedButton.styleFrom(
        foregroundColor: _themeColor.cardInitColor,
        side: BorderSide(
          color: _themeColor.cardInitColor,
        ),
      ),
      icon: const Icon(Icons.cloud_outlined),
      label: Text(l.joinOnline),
    );
  }

  Widget _offlineGame(AppLocalizations l) {
    return OutlinedButton.icon(
      onPressed: () {
        setState(() {
          Model.setConnectionCodeCard(0);
          _message = l.joinedOfflineWithoutUsingAConnectionCode;
        });
      },
      style: OutlinedButton.styleFrom(
        foregroundColor: _themeColor.cardInitColor,
        side: BorderSide(
          color: _themeColor.cardInitColor,
        ),
      ),
      icon: const Icon(Icons.cloud_off_outlined),
      label: Text(l.joinOffline),
    );
  }

  Widget _newCard(AppLocalizations l) {
    return OutlinedButton.icon(
      onPressed: () {
        showDialog(
          context: context,
          builder: (_) {
            return AlertDialog(
              title: Text(l.newCard),
              content: Text(l.replaceWithANewCardIsItOk),
              actions: <Widget>[
                TextButton(
                  child: Text(l.cancel),
                  onPressed: () => Navigator.pop(context),
                ),
                TextButton(
                  child: Text(l.ok),
                  onPressed: () => {
                    Model.cardNew(),
                    Navigator.pop(context),
                  },
                ),
              ],
            );
          },
        );
      },
      style: OutlinedButton.styleFrom(
        foregroundColor: _themeColor.cardInitColor,
        side: BorderSide(
          color: _themeColor.cardInitColor,
        ),
      ),
      icon: const Icon(Icons.insert_drive_file_outlined),
      label: Text(l.newCard),
    );
  }

  Widget _cardPage(AppLocalizations l) {
    return Directionality(
      textDirection: TextDirection.rtl,
      child: ElevatedButton.icon(
        onPressed: () {
          if (Model.connectionCodeCard == 0) {
            Navigator.push(
              context,
              MaterialPageRoute<void>(
                builder: (BuildContext context) => const CardOfflinePage(),
              ),
            );
          } else{
            Navigator.push(
              context,
              MaterialPageRoute<void>(
                builder: (BuildContext context) => const CardPage(),
              ),
            );
          }
        },
        style: ElevatedButton.styleFrom(
          foregroundColor: const Color.fromRGBO(255,255,255,1),
          backgroundColor: _themeColor.cardInitColor,
          elevation: 2,
        ),
        icon: const Icon(Icons.chevron_left),
        label: Text(l.bingoCard),
      )
    );
  }

  void _connectionCodeCardJoin(AppLocalizations l) async {
    if (_inputNumber < 100000 || _inputNumber > 999999) {
      setState(() {
        _message = l.wrongNumber;
      });
      _onlineButtonDisable = false;
      return;
    }
    final int number = await Model.connectionCodeCardJoin(_inputNumber);
    for (int i = 5; i > 0; i--) {
      await Future.delayed(const Duration(milliseconds: 1000));
      setState(() {
        _message = '${l.connecting}.$i';
      });
    }
    if (number == 0) {
      setState(() {
        _message = l.wrongNumberOrHasExpired;
      });
    } else {
      setState(() {
        _message = '${l.connected}: $number';
      });
    }
    _onlineButtonDisable = false;
  }

}
///
/// @author akira ohmachi
/// @copyright ao-system, Inc.
/// @date 2023-01-27
///
library;

import 'package:flutter/material.dart';

import 'package:bingoonline/l10n/app_localizations.dart';
import 'package:bingoonline/model.dart';
import 'package:bingoonline/ad_manager.dart';
import 'package:bingoonline/ad_banner_widget.dart';
import 'package:bingoonline/theme_color.dart';

class CardOfflinePage extends StatefulWidget {
  const CardOfflinePage({super.key});
  @override
  State<CardOfflinePage> createState() => _CardOfflinePageState();
}
class _CardOfflinePageState extends State<CardOfflinePage> {
  late AdManager _adManager;
  late ThemeColor _themeColor;
  bool _isFirst = true;

  @override
  void initState() {
    super.initState();
    _adManager = AdManager();
    Model.cardCellSetOpenClose();
  }

  @override
  void dispose() {
    _adManager.dispose();
    super.dispose();
  }

  void _cellTap(int ptr) {
    final int num = Model.cardCellPtrGetNumber(ptr);
    if (Model.ballHistoryContain(num)) {
      setState(() {
        Model.ballHistoryRemove(num);
      });
    } else {
      setState(() {
        Model.ballHistoryAdd(num);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isFirst) {
      _isFirst = false;
      _themeColor = ThemeColor(themeNumber: Model.themeNumber, context: context);
    }
    final l = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: _themeColor.cardBackColor,
      appBar: AppBar(
        centerTitle: true,
        elevation: 0,
        title: Text(l.cardOffline),
        foregroundColor: const Color.fromRGBO(255,255,255,1),
        backgroundColor: Colors.transparent,
      ),
      body: SafeArea(top: false, left: false, right: false, bottom: true,
        child: Column(children:[
          Expanded(
            child: SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.only(left: 16, right: 16, top: 8, bottom: 100),
                child: Column(
                  children: [
                    Container(
                      decoration: const BoxDecoration(
                        boxShadow: [
                          BoxShadow(
                            color: Color.fromRGBO(0,0,0,0.1),
                            spreadRadius: 2,
                            blurRadius: 2,
                            offset: Offset(0,1), // changes position of shadow
                          ),
                        ],
                      ),
                      child: Table(
                        border: TableBorder.all(width: 4, color: _themeColor.cardFrameColor),
                        columnWidths: const <int, TableColumnWidth>{
                          0: FlexColumnWidth(1),
                          1: FlexColumnWidth(1),
                          2: FlexColumnWidth(1),
                          3: FlexColumnWidth(1),
                          4: FlexColumnWidth(1),
                        },
                        children: [
                          TableRow(children:[_cellBingo('B'),_cellBingo('I'),_cellBingo('N'),_cellBingo('G'),_cellBingo('O')]),
                          TableRow(children:[
                            InkWell(onTap:(){_cellTap(0);},child:_cellNumber(0)),
                            InkWell(onTap:(){_cellTap(5);},child:_cellNumber(5)),
                            InkWell(onTap:(){_cellTap(10);},child:_cellNumber(10)),
                            InkWell(onTap:(){_cellTap(15);},child:_cellNumber(15)),
                            InkWell(onTap:(){_cellTap(20);},child:_cellNumber(20)),
                          ]),
                          TableRow(children:[
                            InkWell(onTap:(){_cellTap(1);},child:_cellNumber(1)),
                            InkWell(onTap:(){_cellTap(6);},child:_cellNumber(6)),
                            InkWell(onTap:(){_cellTap(11);},child:_cellNumber(11)),
                            InkWell(onTap:(){_cellTap(16);},child:_cellNumber(16)),
                            InkWell(onTap:(){_cellTap(21);},child:_cellNumber(21)),
                          ]),
                          TableRow(children:[
                            InkWell(onTap:(){_cellTap(2);},child:_cellNumber(2)),
                            InkWell(onTap:(){_cellTap(7);},child:_cellNumber(7)),
                            InkWell(onTap:(){_cellTap(12);},child:_cellNumber(12)),
                            InkWell(onTap:(){_cellTap(17);},child:_cellNumber(17)),
                            InkWell(onTap:(){_cellTap(22);},child:_cellNumber(22)),
                          ]),
                          TableRow(children:[
                            InkWell(onTap:(){_cellTap(3);},child:_cellNumber(3)),
                            InkWell(onTap:(){_cellTap(8);},child:_cellNumber(8)),
                            InkWell(onTap:(){_cellTap(13);},child:_cellNumber(13)),
                            InkWell(onTap:(){_cellTap(18);},child:_cellNumber(18)),
                            InkWell(onTap:(){_cellTap(23);},child:_cellNumber(23)),
                          ]),
                          TableRow(children:[
                            InkWell(onTap:(){_cellTap(4);},child:_cellNumber(4)),
                            InkWell(onTap:(){_cellTap(9);},child:_cellNumber(9)),
                            InkWell(onTap:(){_cellTap(14);},child:_cellNumber(14)),
                            InkWell(onTap:(){_cellTap(19);},child:_cellNumber(19)),
                            InkWell(onTap:(){_cellTap(24);},child:_cellNumber(24)),
                          ]),
                        ],
                      ),
                    ),
                    Container(height:80),
                  ],
                ),
              ),
            ),
          ),
        ]),
      ),
      bottomNavigationBar: AdBannerWidget(adManager: _adManager),
    );
  }

  Widget _cellBingo(String str) {
    return Container(
      padding: const EdgeInsets.all(5),
      color: _themeColor.cardFrameColor,
      child: Center(child: Text(str, style: TextStyle(color: Colors.white))),
    );
  }

  Widget _cellNumber(int ptr) {
    final int num = Model.cardCellPtrGetNumber(ptr);
    final bool openClose = Model.cardCellPtrGetOpenBool(ptr);
    final String numStr = (num == 0) ? 'FREE' : num.toString();
    final double fontSize = (num == 0) ? 20 : 30;
    Container openMark = Container(
      margin: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: const Color.fromRGBO(255,0,0,0.3),
        border: Border.all(width: 4,color: const Color.fromRGBO(255,50,0,0.2)),
      ),
    );
    Container closeMark = Container();
    return AspectRatio(
      aspectRatio: 1,
      child: Stack(
        children: [
          Container(
            color: _themeColor.cardCellColor,
            child: Center(child: Text(numStr,
              style: TextStyle(
                fontSize: fontSize,
              ),
            )),
          ),
          openClose ? openMark : closeMark,
        ],
      ),
    );
  }

}
///
/// @author akira ohmachi
/// @copyright ao-system, Inc.
/// @date 2023-01-27
///
library;

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

import 'package:bingoonline/l10n/app_localizations.dart';
import 'package:bingoonline/model.dart';
import 'package:bingoonline/progress_table.dart';
import 'package:bingoonline/ad_manager.dart';
import 'package:bingoonline/ad_banner_widget.dart';
import 'package:bingoonline/theme_color.dart';


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

class _CardPageState extends State<CardPage> {
  late Timer _timer;
  bool _timerToggle = false;
  late AdManager _adManager;
  late ThemeColor _themeColor;
  bool _isFirst = true;

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

  void _initState() async {
    _adManager = AdManager();
    Model.cardCellSetOpenClose();
    Model.setConnectionCodeCardWatchFlag(true);
    _timer = Timer.periodic(const Duration(seconds: 5), (timer) {
      _timerToggle = _timerToggle ? false : true;
      Model.connectionCodeCardWatch();
      setState(() {});
      if (Model.connectionCodeCardWatchFlag == false) {
        _timer.cancel();
      }
    });
  }

  @override
  void dispose() {
    Model.setConnectionCodeCardWatchFlag(false);
    _timer.cancel();
    _adManager.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isFirst) {
      _isFirst = false;
      _themeColor = ThemeColor(themeNumber: Model.themeNumber, context: context);
    }
    final l = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: _themeColor.cardBackColor,
      appBar: AppBar(
        centerTitle: true,
        elevation: 0,
        title: Text((Model.connectionCodeCard == 0) ? l.card : Model.connectionCodeCard.toString()),
        backgroundColor: Colors.transparent,
      ),
      body: SafeArea(
        top: false,
        left: false,
        right: false,
        bottom: true,
        child: Column(children:[
          Expanded(
            child: SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.only(left: 16, right: 16, top: 8, bottom: 100),
                child: Column(
                  children: [
                    Container(
                      decoration: const BoxDecoration(
                        boxShadow: [
                          BoxShadow(
                            color: Color.fromRGBO(0,0,0,0.1),
                            spreadRadius: 2,
                            blurRadius: 2,
                            offset: Offset(0,1), // changes position of shadow
                          ),
                        ],
                      ),
                      child: Table(
                        border: TableBorder.all(width: 4, color: _themeColor.cardFrameColor),
                        columnWidths: const <int, TableColumnWidth>{
                          0: FlexColumnWidth(1),
                          1: FlexColumnWidth(1),
                          2: FlexColumnWidth(1),
                          3: FlexColumnWidth(1),
                          4: FlexColumnWidth(1),
                        },
                        children: [
                          TableRow(children:[_cellBingo('B'),_cellBingo('I'),_cellBingo('N'),_cellBingo('G'),_cellBingo('O')]),
                          TableRow(children:[_cellNumber(0),_cellNumber(5),_cellNumber(10),_cellNumber(15),_cellNumber(20)]),
                          TableRow(children:[_cellNumber(1),_cellNumber(6),_cellNumber(11),_cellNumber(16),_cellNumber(21)]),
                          TableRow(children:[_cellNumber(2),_cellNumber(7),_cellNumber(12),_cellNumber(17),_cellNumber(22)]),
                          TableRow(children:[_cellNumber(3),_cellNumber(8),_cellNumber(13),_cellNumber(18),_cellNumber(23)]),
                          TableRow(children:[_cellNumber(4),_cellNumber(9),_cellNumber(14),_cellNumber(19),_cellNumber(24)]),
                        ],
                      ),
                    ),
                    Container(height:30),
                    ProgressTable().table(context, _themeColor),
                  ],
                ),
              ),
            ),
          ),
        ]),
      ),
      bottomNavigationBar: AdBannerWidget(adManager: _adManager),
    );
  }

  Widget _cellBingo(String str) {
    return Container(
      padding: const EdgeInsets.all(5),
      color: _themeColor.cardFrameColor,
      child: Center(child: Text(str,
        style: TextStyle(color: _timerToggle ? Colors.black : Colors.white),
      )),
    );
  }

  Widget _cellNumber(int ptr) {
    final int num = Model.cardCellPtrGetNumber(ptr);
    final bool openClose = Model.cardCellPtrGetOpenBool(ptr);
    final String numStr = (num == 0) ? 'FREE' : num.toString();
    final double fontSize = (num == 0) ? 20 : 30;
    Container openMark = Container(
      margin: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: const Color.fromRGBO(255,0,0,0.3),
        border: Border.all(width: 4,color: const Color.fromRGBO(255,50,0,0.2)),
      ),
    );
    Container closeMark = Container();
    return AspectRatio(
      aspectRatio: 1,
      child: Stack(
        children: [
          Container(
            color: _themeColor.cardCellColor,
            child: Center(child: Text(numStr,
              style: TextStyle(
                fontSize: fontSize,
              ),
            )),
          ),
          openClose ? openMark : closeMark,
        ],
      ),
    );
  }

}
///
/// @author akira ohmachi
/// @copyright ao-system, Inc.
/// @date 2023-01-27
///
library;

import 'package:flutter/material.dart';

import 'package:bingoonline/l10n/app_localizations.dart';
import 'package:bingoonline/const_value.dart';
import 'package:bingoonline/setting_page.dart';
import 'package:bingoonline/machine_init_page.dart';
import 'package:bingoonline/card_init_page.dart';
import 'package:bingoonline/ad_manager.dart';
import 'package:bingoonline/ad_banner_widget.dart';
import 'package:bingoonline/theme_color.dart';
import 'package:bingoonline/theme_mode_number.dart';
import 'package:bingoonline/loading_screen.dart';
import 'package:bingoonline/model.dart';
import 'package:bingoonline/parse_locale_tag.dart';
import 'package:bingoonline/main.dart';

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

class _MainHomePageState extends State<MainHomePage> {
  late AdManager _adManager;
  late ThemeColor _themeColor;
  bool _isReady = false;
  bool _isFirst = true;

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

  void _initState() async {
    _adManager = AdManager();
    setState(() {
      _isReady = true;
    });
  }

  @override
  void dispose() {
    _adManager.dispose();
    super.dispose();
  }

  void _onClickSetting() async {
    final updatedSettings = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => SettingPage(),
      ),
    );
    if (updatedSettings != null) {
      if (mounted) {
        final mainState = context.findAncestorStateOfType<MainAppState>();
        if (mainState != null) {  //MyAppStateに反映する
          mainState
            ..locale = parseLocaleTag(Model.languageCode)
            ..themeMode = ThemeModeNumber.numberToThemeMode(Model.themeNumber)
            ..setState(() {});
          setState(() {
            _isFirst = true;  //再度テーマ更新
          });
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return LoadingScreen();
    }
    if (_isFirst) {
      _isFirst = false;
      _themeColor = ThemeColor(themeNumber: Model.themeNumber, context: context);
    }
    return SafeArea(
      top: false,
      left: false,
      right: false,
      bottom: true,
      child: Scaffold(
        backgroundColor: const Color.fromARGB(255,0,249,140),
        body: Stack(
          children: [
            Container(
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(ConstValue.topBack),
                  fit: BoxFit.cover,
                ),
              ),
            ),
            SafeArea(
              child: Padding(
                padding: const EdgeInsets.only(top: 5, left: 0, right: 10, bottom: 0),
                child: Row(children:[
                  const Spacer(),
                  OutlinedButton(
                    onPressed: _onClickSetting,
                    style: OutlinedButton.styleFrom(
                      foregroundColor: const Color.fromRGBO(0,0,0,0.4),
                      side: const BorderSide(
                        color: Color.fromRGBO(0,0,0,0.4),
                      ),
                    ),
                    child: Text(AppLocalizations.of(context)!.setting),
                  ),
                ]),
              ),
            ),
            Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Directionality(
                    textDirection: TextDirection.rtl,
                    child: ElevatedButton.icon(
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute<void>(
                            builder: (BuildContext context) => const MachineInitPage(),
                          ),
                        );
                      },
                      style: ElevatedButton.styleFrom(
                        foregroundColor: const Color.fromRGBO(255,255,255,1),
                        backgroundColor: const Color.fromRGBO(0,0,0,0.3),
                        elevation: 0,
                      ),
                      icon: const Icon(Icons.chevron_left),
                      label: Text(AppLocalizations.of(context)!.bingoMachine,style: const TextStyle(fontSize:20)),
                    ),
                  ),
                  Container(height: 30),
                  Directionality(
                    textDirection: TextDirection.rtl,
                    child: ElevatedButton.icon(
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute<void>(
                            builder: (BuildContext context) => const CardInitPage(),
                          ),
                        );
                      },
                      style: ElevatedButton.styleFrom(
                        foregroundColor: const Color.fromRGBO(255,255,255,1),
                        backgroundColor: const Color.fromRGBO(0,0,0,0.3),
                        elevation: 0,
                      ),
                      icon: const Icon(Icons.chevron_left),
                      label: Text(AppLocalizations.of(context)!.bingoCard,style: const TextStyle(fontSize:20)),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        bottomNavigationBar: AdBannerWidget(adManager: _adManager),
      )
    );
  }
}
import 'package:flutter/material.dart';

class LoadingScreen extends StatelessWidget {
  const LoadingScreen({super.key});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.green,
      body: const Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Colors.greenAccent),
          backgroundColor: Colors.white,
        ),
      ),
    );
  }
}
///
/// @author akira ohmachi
/// @copyright ao-system, Inc.
/// @date 2023-01-27
///
library;

import 'package:flutter/material.dart';

import 'package:bingoonline/model.dart';
import 'package:bingoonline/theme_color.dart';

class HistoryTable {
  late ThemeColor _themeColor;

  Widget table(BuildContext context, ThemeColor themeColor) {
    _themeColor = themeColor;

    return Wrap(
      spacing: 2, //セル間の横スペース
      runSpacing: 2, //セル間の縦スペース
      children: List.generate(75, (index) {
        return SizedBox(
          width: MediaQuery.of(context).size.width / 10 - 4,
          child: cellHistory(index),
        );
      }),
    );
  }

  Widget cellHistory(int ptr) {
    if (Model.ballHistoryLength() > ptr) {
      return Container(
        padding: const EdgeInsets.symmetric(vertical: 2),
        decoration: BoxDecoration(
          color: (Model.ballHistoryLength() - 1 == ptr)
              ? _themeColor.progressCellColor2
              : _themeColor.progressCellColor1,
          borderRadius: BorderRadius.circular(64),
        ),
        child: Center(
          child: Text(
            Model.ballHistoryValue(ptr).toString(),
            style: const TextStyle(
              fontSize: 16,
            ),
          ),
        ),
      );
    } else {
      return Container();
    }
  }

}
///
/// @author akira ohmachi
/// @copyright ao-system, Inc.
/// @date 2023-01-27
///
library;

import 'package:flutter/material.dart';

import 'package:bingoonline/l10n/app_localizations.dart';
import 'package:bingoonline/machine_page.dart';
import 'package:bingoonline/model.dart';
import 'package:bingoonline/ad_manager.dart';
import 'package:bingoonline/ad_banner_widget.dart';
import 'package:bingoonline/theme_color.dart';


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

class _MachineInitPageState extends State<MachineInitPage> {
  late AdManager _adManager;
  int _machineSpeed = 1;
  bool _onlineButtonDisable = false;
  String _connectionMessage = '';
  late ThemeColor _themeColor;
  int _themeNumber = 0;
  bool _isFirst = true;

  @override
  void initState() {
    super.initState();
    _adManager = AdManager();
    _themeNumber = Model.themeNumber;
  }

  @override
  void dispose() {
    _adManager.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isFirst) {
      _isFirst = false;
      _themeColor = ThemeColor(themeNumber: _themeNumber, context: context);
    }
    final l = AppLocalizations.of(context)!;
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        elevation: 0,
        title: Text(l.machineSetting, style: TextStyle(color: _themeColor.machineForeColor)),
      ),
      body: SafeArea(
        top: false,
        left: false,
        right: false,
        bottom: true,
        child: Column(children:[
          Expanded(
            child: GestureDetector(
              onTap: () => FocusScope.of(context).unfocus(),  //背景タップでキーボードを仕舞う
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.only(top: 0, left: 12, right: 12, bottom: 100),
                  child: Column(
                    children: [
                      _buildSection1(l),
                      _buildSection2(l),
                      _buildSection3(l),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ]),
      ),
      bottomNavigationBar: AdBannerWidget(adManager: _adManager),
    );
  }

  Widget _buildSection1(AppLocalizations l) {
    return SizedBox(
        width: double.infinity,
        child: Card(
            margin: const EdgeInsets.only(top: 12),
            color: _themeColor.cardColor,
            elevation: 0,
            shadowColor: Colors.transparent,
            surfaceTintColor: Colors.transparent,
            child: Padding(
                padding: const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 16),
                child: Column(
                    children: [
                      SizedBox(
                        child: Text(l.giveTheConnectionCodeToTheParticipant,
                          style: Theme.of(context).textTheme.bodySmall,
                          textAlign: TextAlign.left,
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 8),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children:[
                            _onlineGame(l),
                            const SizedBox(height:1),
                            _offlineGame(l),
                          ]
                        )
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 8),
                        child: SizedBox(
                          child: Text(l.connectionCode,
                            style: Theme.of(context).textTheme.bodySmall,
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 8),
                        child: SizedBox(
                          child: Text(
                            Model.getConnectionCodeMachineStr(),
                            style: const TextStyle(fontSize: 80),
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 8),
                        child: SizedBox(
                          child: Text(_connectionMessage,
                            style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Colors.redAccent),
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                    ]
                )
            )
        )
    );
  }

  Widget _buildSection2(AppLocalizations l) {
    return SizedBox(
      width: double.infinity,
      child: Card(
        margin: const EdgeInsets.only(top: 12),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Padding(
          padding: const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 16),
          child: Column(
            children: [
              Padding(
                padding: const EdgeInsets.only(top: 8),
                child: SizedBox(
                  child: Text(l.initializeTheLotteryResults,
                    style: Theme.of(context).textTheme.bodySmall,
                    textAlign: TextAlign.left,
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 2),
                child: _newGame(l),
              ),
            ]
          )
        )
      )
    );
  }

  Widget _buildSection3(AppLocalizations l) {
    return SizedBox(
      width: double.infinity,
      child: Card(
        margin: const EdgeInsets.only(top: 12),
        color: _themeColor.cardColor,
        elevation: 0,
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
        child: Padding(
          padding: const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 16),
          child: Column(
            children: [
              _machinePage(l),
              Padding(
                padding: const EdgeInsets.only(top: 8),
                child: Center(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children:[
                      Text(l.speed),
                      const SizedBox(width:10),
                      DropdownButton(
                        items: const [
                          DropdownMenuItem(value:1,child:Text('1')),
                          DropdownMenuItem(value:2,child:Text('2')),
                          DropdownMenuItem(value:3,child:Text('3')),
                          DropdownMenuItem(value:4,child:Text('4')),
                          DropdownMenuItem(value:5,child:Text('5')),
                        ],
                        onChanged: (int? value) {
                          setState(() {
                            _machineSpeed = value!;
                          });
                        },
                        value: _machineSpeed,
                      ),
                    ]
                  ),
                ),
              ),
            ]
          )
        )
      )
    );
  }

  Widget _onlineGame(AppLocalizations l) {
    return OutlinedButton.icon(
      onPressed: _onlineButtonDisable ? null : () {
        showDialog(
          context: context,
          builder: (_) {
            return AlertDialog(
              title: Text(l.heldOnline),
              content: Text(l.connectionCodeWillBeIssuedIsItOk),
              actions: <Widget>[
                TextButton(
                  child: Text(l.cancel),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ),
                TextButton(
                  child: Text(l.ok),
                  onPressed: () {
                    Navigator.pop(context);
                    _connectionCodeMachineCreate(l);
                  },
                ),
              ],
            );
          },
        );
      },
      style: OutlinedButton.styleFrom(
          foregroundColor: _themeColor.machineForeColor,
          side: BorderSide(
            color: _themeColor.machineForeColor,
          ),
      ),
      icon: const Icon(Icons.cloud_outlined),
      label: Text(l.heldOnline),
    );
  }

  Widget _offlineGame(AppLocalizations l) {
    return OutlinedButton.icon(
      onPressed: () {
        showDialog(
          context: context,
          builder: (_) {
            return AlertDialog(
              title: Text(l.heldOffline),
              content: Text(l.connectionCodeWillBeInvalidIsItOk),
              actions: <Widget>[
                TextButton(
                  child: Text(l.cancel),
                  onPressed: () => Navigator.pop(context),
                ),
                TextButton(
                  child: Text(l.ok),
                  onPressed: () => {
                    setState(() {
                      Model.setConnectionCodeMachine(0);
                      _connectionMessage = l.connectionCodeIsNoLongerValid;
                    }),
                    Navigator.pop(context),
                  },
                ),
              ],
            );
          },
        );
      },
      style: OutlinedButton.styleFrom(
        foregroundColor: _themeColor.machineForeColor,
        side: BorderSide(
          color: _themeColor.machineForeColor,
        ),
      ),
      icon: const Icon(Icons.cloud_off_outlined),
      label: Text(l.heldOffline),
    );
  }

  Widget _newGame(AppLocalizations l) {
    return OutlinedButton.icon(
      onPressed: () {
        showDialog(
          context: context,
          builder: (_) {
            return AlertDialog(
              title: Text(l.newGame),
              content: Text(l.lotteryResultIsInitializedIsItOk),
              actions: <Widget>[
                TextButton(
                  child: Text(l.cancel),
                  onPressed: () => Navigator.pop(context),
                ),
                TextButton(
                  child: Text(l.ok),
                  onPressed: () => {
                    _connectionCodeMachineClear(l),
                    Navigator.pop(context),
                  },
                ),
              ],
            );
          },
        );
      },
      style: OutlinedButton.styleFrom(
        foregroundColor: _themeColor.machineForeColor,
        side: BorderSide(
          color: _themeColor.machineForeColor,
        ),
      ),
      icon: const Icon(Icons.insert_drive_file_outlined),
      label: Text(l.newGame),
    );
  }

  Widget _machinePage(AppLocalizations l) {
    return Directionality(
        textDirection: TextDirection.rtl,
        child: ElevatedButton.icon(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute<void>(
                builder: (BuildContext context) => MachinePage(machineSpeed: _machineSpeed),
              ),
            );
          },
          style: ElevatedButton.styleFrom(
            foregroundColor: const Color.fromRGBO(255,255,255,1),
            backgroundColor: _themeColor.machineForeColor,
            elevation: 2,
          ),
          icon: const Icon(Icons.chevron_left),
          label: Text(l.bingoMachine),
        )
    );
  }

  void _connectionCodeMachineCreate(AppLocalizations l) async {
    setState(() {
      _onlineButtonDisable = true;
      _connectionMessage = l.connectionCodeIsBeingIssued;
    });
    final int number = await Model.connectionCodeMachineCreate();
    for (int i = 10; i > 0; i--) {
      await Future.delayed(const Duration(milliseconds: 1000));
      setState(() {
        _connectionMessage = l.connectionCodeIsBeingIssued + i.toString();
      });
    }
    setState(() {
      _onlineButtonDisable = false;
      _connectionMessage = (number == 0) ? l.failedToConnectPleaseTryAgain : l.connectionCodeHasBeenIssued;
    });
  }

  void _connectionCodeMachineClear(AppLocalizations l) async {
    final bool ret = await Model.connectionCodeMachineClear();
    setState(() {
      _connectionMessage = (ret) ? l.theLotteryResultsHaveBeenInitialized : l.failedToInitializeLotteryResults;
    });
  }
}
///
/// @author akira ohmachi
/// @copyright ao-system, Inc.
/// @date 2023-01-27
///
library;

import 'dart:async';
import 'package:bingoonline/loading_screen.dart';
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:video_player/video_player.dart';
import 'package:flutter_svg/flutter_svg.dart';

import 'package:bingoonline/l10n/app_localizations.dart';
import 'package:bingoonline/model.dart';
import 'package:bingoonline/text_to_speech.dart';
import 'package:bingoonline/machine_history_table.dart';
import 'package:bingoonline/progress_table.dart';
import 'package:bingoonline/ad_manager.dart';
import 'package:bingoonline/ad_banner_widget.dart';
import 'package:bingoonline/theme_color.dart';


class MachinePage extends StatefulWidget {
  const MachinePage({super.key, required this.machineSpeed});
  final int machineSpeed;
  @override
  State<MachinePage> createState() => _MachinePageState();
}
class _MachinePageState extends State<MachinePage> {
  VideoPlayerController? _videoController;
  Completer<void>? _videoPreparingCompleter;
  late double _ballSizeMax;
  late double _ballTextSizeMax;
  Duration _movieDuration = const Duration(milliseconds: 7000);
  double _ballSize = 0;
  double _ballTextSize = 0;
  double _ballTextMarginSize = 0;
  Duration _ballAnimationDuration = const Duration(milliseconds: 0);
  final Duration _ballAnimationDurationMin = const Duration(milliseconds: 0);
  final Duration _ballAnimationDurationMax = const Duration(milliseconds: 500);
  int _ballNumber = 0;
  bool _startButtonIsDisabled = false;
  String _message = '';
  bool _speakFlag = true;
  double _machineVolumeGain = 1.0;
  late AudioPlayer _audio;
  late AdManager _adManager;
  bool _isReady = false;
  late ThemeColor _themeColor;
  int _themeNumber = 0;
  bool _isFirst = true;

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

  void _initState() async {
    _adManager = AdManager();
    _audio = AudioPlayer();
    unawaited(_initializeVideoPlayer());
    double audioRatio = 1.0;
    if (widget.machineSpeed == 1) {
      _movieDuration = const Duration(milliseconds: 6900);
      audioRatio = 1.0;
    } else if (widget.machineSpeed == 2) {
      _movieDuration = const Duration(milliseconds: 3300);
      audioRatio = 2.0;
    } else if (widget.machineSpeed == 3) {
      _movieDuration = const Duration(milliseconds: 2100);
      audioRatio = 3.0;
    } else if (widget.machineSpeed == 4) {
      _movieDuration = const Duration(milliseconds: 1600);
      audioRatio = 4.0;
    } else if (widget.machineSpeed == 5) {
      _movieDuration = const Duration(milliseconds: 1100);
      audioRatio = 5.0;
    }
    await _audio.setSource(AssetSource('sound/machine.wav'));
    await _audio.setReleaseMode(ReleaseMode.stop);
    await _audio.setVolume(Model.machineVolume);
    await _audio.setPlaybackRate(audioRatio);
    Future.delayed(Duration(milliseconds: 500), () {
      setState(() {
        _isReady = true;
      });
    });
  }
  @override
  void dispose() {
    final controller = _videoController;
    _videoController = null;
    if (controller != null) {
      unawaited(controller.dispose());
    }
    _audio.dispose();
    _adManager.dispose();
    super.dispose();
  }

  Future<void> _playMachineSound() async {
    if (_machineVolumeGain > 0) {
      try {
        await _audio.seek(Duration.zero);
        await Future.delayed(Duration(milliseconds: 100));
        await _audio.resume();
      } catch (_) {}
    }
  }

  Future<VideoPlayerController> _createVideoController() async {
    final controller = VideoPlayerController.asset('assets/movie/bingo4mbps.mp4',
      videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true),
    );
    await controller.initialize();
    return controller;
  }

  Future<void> _initializeVideoPlayer({bool autoPlay = false, bool recreate = false}) async {
    while (_videoPreparingCompleter != null) {
      await _videoPreparingCompleter!.future;
    }
    final completer = Completer<void>();
    _videoPreparingCompleter = completer;
    VideoPlayerController? previousController;
    bool replacedController = false;
    try {
      previousController = recreate ? _videoController : null;
      if (previousController != null) {
        try {
          await previousController.pause();
        } catch (_) {}
      }
      final controller = await _createVideoController();
      await controller.setPlaybackSpeed(widget.machineSpeed.toDouble());
      if (!mounted) {
        await controller.dispose();
        return;
      }
      setState(() {
        _videoController = controller;
      });
      replacedController = true;
      if (autoPlay) {
        try {
          await controller.play();
        } catch (_) {}
      }
    } finally {
      if (replacedController && previousController != null) {
        unawaited(previousController.dispose());
      }
      if (!completer.isCompleted) {
        completer.complete();
      }
      _videoPreparingCompleter = null;
    }
  }

  Future<void> _restartMachineVideo() async {
    await _initializeVideoPlayer(autoPlay: true, recreate: true);
  }

  void _updateBallMetrics(BuildContext context) {
    _ballSizeMax = MediaQuery.of(context).size.width / 2;
    _ballTextSizeMax = _ballSizeMax * 0.8;
    _ballTextMarginSize = (_ballSizeMax - _ballTextSizeMax) / 2;
  }

  int nextBallNumber() {
    List<int> numbers = [];
    for (int i = 1; i <= 75; i++) {
      if (Model.ballHistoryContain(i) == false) {
        numbers.add(i);
      }
    }
    if (numbers.isEmpty) {
      return 0;
    }
    numbers.shuffle();
    return numbers[0];
  }

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return LoadingScreen();
    }
    if (_isFirst) {
      _isFirst = false;
      _themeColor = ThemeColor(themeNumber: _themeNumber, context: context);
    }
    _updateBallMetrics(context);
    final int connectionCodeMachine = Model.connectionCodeMachine;
    final l = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: _themeColor.machineMovieBackColor,
      appBar: AppBar(
        centerTitle: true,
        elevation: 0,
        title: Text((connectionCodeMachine == 0) ? l.bingoMachine : connectionCodeMachine.toString()),
        backgroundColor: Colors.transparent,
      ),
      body: SafeArea(top: false, left: false, right: false, bottom: true,
        child: ListView(
          padding: const EdgeInsets.only(left: 8, right: 8, top: 0, bottom: 100),
          children: [
            _buildVideoSection(context),
            _buildMessageSection(),
            HistoryTable().table(context, _themeColor),
            const SizedBox(height: 20),
            ProgressTable().table(context, _themeColor),
          ],
        ),
      ),
      bottomNavigationBar: AdBannerWidget(adManager: _adManager),
    );
  }

  Widget _buildVideoSection(BuildContext context) {
    final l = AppLocalizations.of(context)!;
    return Stack(
      children: [
        AspectRatio(aspectRatio: 1,
          child: _buildVideoPlayer(),
        ),
        Positioned(
          bottom: 3,
          right: 7,
          child: OutlinedButton(
            onPressed: _startButtonIsDisabled
              ? null
              : () async {
                final endedMessage = l.ended;
                final failedMessage = l.failedToConnect;
                setState(() {
                  _startButtonIsDisabled = true;
                  _ballAnimationDuration = _ballAnimationDurationMin;
                  _ballSize = 0;
                  _ballTextSize = 0;
                  _message = '';
                });
                try {
                  unawaited(_playMachineSound());
                  await _restartMachineVideo();

                  await Future.delayed(_movieDuration);
                  if (!mounted) {
                    return;
                  }
                  setState(() {
                    _ballNumber = nextBallNumber();
                    _ballAnimationDuration = _ballAnimationDurationMax;
                    _ballSize = _ballSizeMax;
                    _ballTextSize = _ballTextSizeMax;
                  });
                  await Future.delayed(_ballAnimationDurationMax);
                  if (!mounted) {
                    return;
                  }
                  if (_ballNumber != 0 && _speakFlag) {
                    TextToSpeech.speak(_ballNumber.toString());
                  }
                  await Future.delayed(_ballAnimationDurationMax);
                  if (!mounted) {
                    return;
                  }
                  String message = '';
                  if (_ballNumber == 0) {
                    message = endedMessage;
                  } else {
                    final bool ret = await Model.ballHistoryAdd(_ballNumber);
                    if (!mounted) {
                      return;
                    }
                    if (!ret) {
                      message = failedMessage;
                    }
                  }
                  if (!mounted) {
                    return;
                  }
                  setState(() {
                    _message = message;
                  });
                  await Future.delayed(const Duration(milliseconds: 800));
                } finally {
                  if (mounted) {
                    setState(() {
                      _startButtonIsDisabled = false;
                    });
                  }
                }
              },
            style: OutlinedButton.styleFrom(
              foregroundColor: Colors.white,
              side: const BorderSide(
                color: Colors.white,
              ),
            ),
            child: Text(l.start),
          ),
        ),
        Container(
          margin: const EdgeInsets.only(left: 8, top: 8),
          child: Stack(
            children: [
              SizedBox(
                child: AnimatedContainer(
                  duration: _ballAnimationDuration,
                  width: _ballSize,
                  height: _ballSize,
                  child: SvgPicture.asset('assets/image/ball.svg'),
                ),
              ),
              Positioned(
                top: _ballTextMarginSize,
                left: _ballTextMarginSize,
                child: SizedBox(
                  child: AnimatedContainer(
                    duration: _ballAnimationDuration,
                    width: _ballTextSize,
                    height: _ballTextSize,
                    child: FittedBox(
                      fit: BoxFit.fitWidth,
                      child: Text(
                        (_ballNumber == 0) ? 'END' : _ballNumber.toString(),
                        style: const TextStyle(color: Colors.black, fontWeight: FontWeight.w700),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        )
      ],
    );
  }

  Widget _buildVideoPlayer() {
    final controller = _videoController;
    if (controller != null && controller.value.isInitialized) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(24),
        child: VideoPlayer(controller),
      );
    }
    return Container(
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(24),
      ),
    );
  }

  Widget _buildMessageSection() {
    return Padding(
      padding: const EdgeInsets.only(top: 2, bottom: 30),
      child: Text(_message,
        style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Colors.redAccent),
        textAlign: TextAlign.center,
      ),
    );
  }

}
///
/// @author akira ohmachi
/// @copyright ao-system, Inc.
/// @date 2023-01-27
///
library;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'package:bingoonline/l10n/app_localizations.dart';
import 'package:bingoonline/loading_screen.dart';
import 'package:bingoonline/model.dart';
import 'package:bingoonline/theme_mode_number.dart';
import 'package:bingoonline/parse_locale_tag.dart';
import 'package:bingoonline/home_page.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
  SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
    statusBarColor: Colors.transparent,
    systemNavigationBarColor: Colors.transparent,
  ));
  MobileAds.instance.initialize();
  runApp(const MainApp());
}

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

class MainAppState extends State<MainApp> {
  ThemeMode themeMode = ThemeMode.light;
  Locale? locale;
  bool _isReady = false;

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

  void _initState() async {
    await Model.ensureReady();
    themeMode = ThemeModeNumber.numberToThemeMode(Model.themeNumber);
    locale = parseLocaleTag(Model.languageCode);
    setState(() {
      _isReady = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (!_isReady) {
      return MaterialApp(
        home: Scaffold(
          body: Center(
            child: LoadingScreen(),
          ),
        ),
      );
    }
    const seed = Colors.green;
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
      locale: locale,
      themeMode: themeMode,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: seed),
        useMaterial3: true,
      ),
      darkTheme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: seed,
          brightness: Brightness.dark,
        ),
        useMaterial3: true,
      ),
      home: const MainHomePage(),
    );
  }
}
///
/// @author akira ohmachi
/// @copyright ao-system, Inc.
/// @date 2023-01-27
///
library;

import 'dart:async';
import 'dart:convert' as convert;
import 'package:http/http.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

import 'package:bingoonline/card_cell.dart';
import 'package:bingoonline/const_value.dart';

class Model {
  Model._();

  static const String _prefConnectionCodeMachine = 'connectionCodeMachine';
  static const String _prefConnectionCodeMachineTimestamp = 'connectionCodeMachineTimestamp';
  static const String _prefConnectionCodeCard = 'connectionCodeCard';
  static const String _prefBallHistories = 'ballHistories';
  static const String _prefCardNumbers = 'cardNumbers';
  static const String _prefMachineVolume = 'machineVolume';
  static const String _prefTtsEnabled = 'ttsEnabled';
  static const String _prefTtsVolume = 'ttsVolume';
  static const String _prefTtsVoiceId = 'ttsVoiceId ';
  static const String _prefThemeNumber = "themeNumber";
  static const String _prefLanguageCode = 'languageCode';

  static bool _ready = false;
  static int _connectionCodeMachine = 0;
  static int _connectionCodeMachineTimestamp = 0;
  static int _connectionCodeCard = 0;
  static List<int> _ballHistories = [];
  static List<int> _cardNumbers = [];
  static double _machineVolume = 1.0;
  static bool _ttsEnabled = true;
  static double _ttsVolume = 1.0;
  static String _ttsVoiceId = '';
  static int _themeNumber = 0;
  static String _languageCode = '';
  //
  static bool _connectionCodeCardWatchFlag = false;
  static int _connectionErrorCount = 0;
  static int _lastBallHistoryLength = 0;
  static int _sameLastBallHistoryLengthCount = 0;

  static final List<CardCell> _cardCells = [
    CardCell(1, 0),
    CardCell(2, 0),
    CardCell(3, 0),
    CardCell(4, 0),
    CardCell(5, 0),
    CardCell(16, 0),
    CardCell(17, 0),
    CardCell(18, 0),
    CardCell(19, 0),
    CardCell(20, 0),
    CardCell(31, 0),
    CardCell(32, 0),
    CardCell(0, 1),
    CardCell(34, 0),
    CardCell(35, 0),
    CardCell(46, 0),
    CardCell(47, 0),
    CardCell(48, 0),
    CardCell(49, 0),
    CardCell(50, 0),
    CardCell(61, 0),
    CardCell(62, 0),
    CardCell(63, 0),
    CardCell(64, 0),
    CardCell(65, 0),
  ];

  static int get connectionCodeMachine => _connectionCodeMachine;
  static int get connectionCodeMachineTimestamp => _connectionCodeMachineTimestamp;
  static int get connectionCodeCard => _connectionCodeCard;
  static List<int> get ballHistories => _ballHistories;
  static List<int> get cardNumbers => _cardNumbers;
  static double get machineVolume => _machineVolume;
  static bool get ttsEnabled => _ttsEnabled;
  static double get ttsVolume => _ttsVolume;
  static String get ttsVoiceId => _ttsVoiceId;
  static int get themeNumber => _themeNumber;
  static String get languageCode => _languageCode;
  static bool get connectionCodeCardWatchFlag => _connectionCodeCardWatchFlag;

  static Future<void> ensureReady() async {
    if (_ready) {
      return;
    }
    final prefs = await SharedPreferences.getInstance();
    //
    _connectionCodeMachine = (prefs.getInt(_prefConnectionCodeMachine) ?? 0).clamp(0, 999999);
    _connectionCodeMachineTimestamp = prefs.getInt(_prefConnectionCodeMachineTimestamp) ?? 0;
    _connectionCodeCard = (prefs.getInt(_prefConnectionCodeCard) ?? 0).clamp(0, 999999);
    _ballHistories = (prefs.getString(_prefBallHistories) ?? '')
        .split(',')
        .where((item) => item.isNotEmpty)
        .map<int>((item) => int.parse(item))
        .toList();
    _cardNumbers = (prefs.getString(_prefCardNumbers) ?? '')
        .split(',')
        .where((item) => item.isNotEmpty)
        .map<int>((item) => int.parse(item))
        .toList();
    _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) ?? '';
    _languageCode = prefs.getString(_prefLanguageCode) ?? '';
    _themeNumber = (prefs.getInt(_prefThemeNumber) ?? 0).clamp(0, 2);
    _ready = true;
  }

  static Future<void> setConnectionCodeMachine(int value) async {
    _connectionCodeMachine = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefConnectionCodeMachine, value);
  }

  static Future<void> setConnectionCodeCard(int value) async {
    _connectionCodeCard = value;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefConnectionCodeCard, 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 prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_prefTtsEnabled, value);
  }

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

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

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

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

  //---------------------------------------------

  //ボール履歴をクリア
  static void _ballHistoryClear() async {
    _ballHistories.clear();
    _cardCellAllClose();
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_prefBallHistories);
  }
  //ボールを追加
  static Future<bool> ballHistoryAdd(int value) async {
    if (_ballHistories.contains(value)) {  //2重登録防止
      return true;
    }
    _ballHistories.add(value);
    cardCellSetOpenClose();
    final String str = _ballHistories.map<String>((int value) => value.toString()).join(',');
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefBallHistories,str);
    if (await _connectionCodeMachineSetBallHistory() == false) {
      return false;
    }
    return true;
  }
  //ボールを履歴から削除
  static Future<bool> ballHistoryRemove(int num) async {
    if (_ballHistories.contains(num) == false) {
      return true;
    }
    _ballHistories.remove(num);
    cardCellSetOpenClose();
    final String str = _ballHistories.map<String>((int value) => value.toString()).join(',');
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefBallHistories,str);
    if (await _connectionCodeMachineSetBallHistory() == false) {   //オフライン想定なのでサーバーに送信されることは無い
      return false;
    }
    return true;
  }
  //ボール履歴に含まれるか
  static bool ballHistoryContain(int num) {
    return _ballHistories.contains(num);
  }
  //ボール履歴の最後か
  static bool ballHistoryIsLast(int num) {
    if (_ballHistories.isEmpty) {
      return false;
    }
    return (_ballHistories[_ballHistories.length - 1] == num) ? true : false;
  }
  //ボール履歴の長さ
  static int ballHistoryLength() {
    return _ballHistories.length;
  }
  //ボール履歴の値
  static int ballHistoryValue(int ptr) {
    if (_ballHistories.isEmpty) {
      return 0;
    }
    if (_ballHistories.length <= ptr) {
      return 0;
    }
    return _ballHistories[ptr];
  }

  //---------------------------------------------

  //新しいカードを用意
  static void cardNew() async {
    List<List<int>> cells = [
      [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
      [16,17,18,19,20,21,22,23,24,25,26,27,28,29,30],
      [31,32,33,34,35,36,37,38,39,40,41,42,43,44,45],
      [46,47,48,49,50,51,52,53,54,55,56,57,58,59,60],
      [61,62,63,64,65,66,67,68,69,70,71,72,73,74,75],
    ];
    cells[0].shuffle();
    cells[1].shuffle();
    cells[2].shuffle();
    cells[3].shuffle();
    cells[4].shuffle();
    _cardCells[0] = CardCell(cells[0][0], 0);
    _cardCells[1] = CardCell(cells[0][1], 0);
    _cardCells[2] = CardCell(cells[0][2], 0);
    _cardCells[3] = CardCell(cells[0][3], 0);
    _cardCells[4] = CardCell(cells[0][4], 0);
    _cardCells[5] = CardCell(cells[1][0], 0);
    _cardCells[6] = CardCell(cells[1][1], 0);
    _cardCells[7] = CardCell(cells[1][2], 0);
    _cardCells[8] = CardCell(cells[1][3], 0);
    _cardCells[9] = CardCell(cells[1][4], 0);
    _cardCells[10] = CardCell(cells[2][0], 0);
    _cardCells[11] = CardCell(cells[2][1], 0);
    _cardCells[12] = CardCell(0, 1);
    _cardCells[13] = CardCell(cells[2][2], 0);
    _cardCells[14] = CardCell(cells[2][3], 0);
    _cardCells[15] = CardCell(cells[3][0], 0);
    _cardCells[16] = CardCell(cells[3][1], 0);
    _cardCells[17] = CardCell(cells[3][2], 0);
    _cardCells[18] = CardCell(cells[3][3], 0);
    _cardCells[19] = CardCell(cells[3][4], 0);
    _cardCells[20] = CardCell(cells[4][0], 0);
    _cardCells[21] = CardCell(cells[4][1], 0);
    _cardCells[22] = CardCell(cells[4][2], 0);
    _cardCells[23] = CardCell(cells[4][3], 0);
    _cardCells[24] = CardCell(cells[4][4], 0);
    //
    List<int> numbers = [];
    for (int i = 0; i < 25; i++) {
      numbers.add(_cardCells[i].number);
    }
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefCardNumbers,numbers.join(','));
  }
  //カードが初期状態なら新しいカードを用意
  static void cardIsInitialToNew() async {
    if (_cardCells[0].getNumber() != 1 || _cardCells[1].getNumber() != 2 || _cardCells[2].getNumber() != 3 || _cardCells[3].getNumber() != 4 || _cardCells[4].getNumber() != 5) {
      return;
    }
    if (_cardCells[5].getNumber() != 16 || _cardCells[6].getNumber() != 17 || _cardCells[7].getNumber() != 18 || _cardCells[8].getNumber() != 19 || _cardCells[9].getNumber() != 20) {
      return;
    }
    final String str = _cardNumbers.map<String>((int value) => value.toString()).join(',');
    if (str.isEmpty) {
      cardNew();
    } else {
      List<String> ary = str.split(',');
      for (int i = 0; i < 25; i++) {
        _cardCells[i].setNumber(int.parse(ary[i]));
      }
    }
  }
  //カードのセルを全て閉じる
  static void _cardCellAllClose() {
    for (int i = 0; i < 25; i++) {
      _cardCells[i].setOpen(0);
    }
    _cardCells[12].setOpen(1);
  }
  //カードのセルをボール履歴でopen/closeをセットする
  static void cardCellSetOpenClose() {
    for (int i = 0; i < 25; i++) {
      final int num = _cardCells[i].getNumber();
      if (_ballHistories.contains(num) || num == 0) {
        _cardCells[i].setOpen(1);
      } else {
        _cardCells[i].setOpen(0);
      }
    }
  }
  //カードのセル位置の番号を返す
  static int cardCellPtrGetNumber(int ptr) {
    return _cardCells[ptr].getNumber();
  }
  //カードのセル位置のopen/closeをboolで返す
  static bool cardCellPtrGetOpenBool(int ptr) {
    return (_cardCells[ptr].getOpen() == 1) ? true : false;
  }

  //---------------------------------------------

  //マシン接続コードを文字列で返す
  static String getConnectionCodeMachineStr() {
    if (_connectionCodeMachine == 0) {
      return '------';
    }
    return _connectionCodeMachine.toString();
  }
  //マシン接続コードをリモート側で生成
  static Future<int> connectionCodeMachineCreate() async {
    final Uri url = Uri.https(ConstValue.apiUrl,'',{'mode':'create'});
    final Response? response = await _getWithTimeout(url);
    int number = 0;
    if (response != null && response.statusCode == 200) {
      final Map<String,dynamic> json = convert.jsonDecode(response.body) as Map<String,dynamic>;
      number = json['number'];
    }
    _connectionCodeMachine = number;
    await setConnectionCodeMachine(_connectionCodeMachine);
    await _connectionCodeMachineTimestampUpdate();  //マシン接続コードタイムスタンプを更新(新規作成)
    return number;
  }
  //マシン接続コードのボール履歴をクリア
  static Future<bool> connectionCodeMachineClear() async {
    _ballHistoryClear();
    if (_connectionCodeMachine == 0) {
      return true;  //成功
    }
    await _connectionCodeMachineTimestampUpdate();  //マシン接続コードタイムスタンプを更新
    final Uri url = Uri.https(ConstValue.apiUrl,'',{'mode':'set','number':_connectionCodeMachine.toString(),'ball_history':''});
    final Response? response = await _getWithTimeout(url);
    if (response != null && response.statusCode == 200) {
      return true;  //成功
    }
    return false; //失敗
  }
  //マシン接続コードのボール履歴をリモートへ送信
  static Future<bool> _connectionCodeMachineSetBallHistory() async {
    if (_connectionCodeMachine == 0) {
      return true;  //成功
    }
    await _connectionCodeMachineTimestampUpdate();  //マシン接続コードタイムスタンプを更新
    final Uri url = Uri.https(ConstValue.apiUrl,'',{'mode':'set','number':_connectionCodeMachine.toString(),'ball_history':_ballHistories.join(',')});
    final Response? response = await _getWithTimeout(url);
    if (response != null && response.statusCode == 200) {
      return true;  //成功
    }
    return false; //失敗
  }
  //マシン接続コードのタイムスタンプを保存(更新)
  static Future<void> _connectionCodeMachineTimestampUpdate() async {
    _connectionCodeMachineTimestamp = (DateTime.now().millisecondsSinceEpoch / 1000).floor();
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_prefConnectionCodeMachineTimestamp, _connectionCodeMachineTimestamp);
  }

  //---------------------------------------------

  //カードがリモートへ確認するフラグをセット
  static void setConnectionCodeCardWatchFlag(bool value) {
    _connectionCodeCardWatchFlag = value;
    _connectionErrorCount = 0;
  }

  //---------------------------------------------

  //カード接続コードでボール履歴を取得
  static Future<int> connectionCodeCardJoin(int inputNumber) async {
    _connectionCodeCard = 0;
    final Uri url = Uri.https(ConstValue.apiUrl,'',{'mode':'get','number':inputNumber.toString()});
    final Response? response = await _getWithTimeout(url);
    if (response != null && response.statusCode == 200) {
      final Map<String,dynamic> json = convert.jsonDecode(response.body) as Map<String,dynamic>;
      final int number = json['number'];
      final String history = json['ball_history'];
      if (inputNumber == number) {
        _connectionCodeCard = inputNumber;
        _ballHistories = [];
        history.split(',').forEach((n) {
          final int num = int.tryParse(n) ?? 0;
          if (num != 0) {
            _ballHistories.add(num);
          }
        });
        cardCellSetOpenClose();
      }
    }
    await setConnectionCodeCard(_connectionCodeCard);
    return _connectionCodeCard;   //0は失敗、それ以外は成功
  }
  //カード接続コードでボール履歴をウオッチ
  static Future<bool> connectionCodeCardWatch() async {
    if (_connectionCodeCardWatchFlag == false || _connectionCodeCard == 0) {
      return true;
    }
    final Uri url = Uri.https(ConstValue.apiUrl,'',{'mode':'get','number':_connectionCodeCard.toString()});
    final Response? response = await _getWithTimeout(url);
    if (response != null && response.statusCode == 200) {
      final Map<String,dynamic> json = convert.jsonDecode(response.body) as Map<String,dynamic>;
      final int number = json['number'];
      final String history = json['ball_history'];
      if (_connectionCodeCard == number) {
        _ballHistories = [];
        history.split(',').forEach((n) {
          final int num = int.tryParse(n) ?? 0;
          if (num != 0) {
            _ballHistories.add(num);
          }
        });
        cardCellSetOpenClose();
        if (_lastBallHistoryLength != _ballHistories.length) {
          _lastBallHistoryLength = _ballHistories.length;
          _sameLastBallHistoryLengthCount = 0;
        } else {
          _sameLastBallHistoryLengthCount += 1;
        }
        if (_sameLastBallHistoryLengthCount > 360) { //60/5秒*30分 30分間マシンが放置の場合は更新を停止
          _connectionCodeCardWatchFlag = false;
          return false;
        }
        _connectionErrorCount = 0;
        return true;
      }
    }
    _connectionErrorCount += 1;
    if (_connectionErrorCount > 10) { //接続エラーが10回続いた場合は更新を停止
      _connectionCodeCardWatchFlag = false;
      return false;
    }
    return true;
  }

  static Future<Response?> _getWithTimeout(Uri url) async {
    try {
      return await http.get(url).timeout(Duration(seconds: 5));
    } on TimeoutException {
      return null;
    } catch (_) {
      return null;
    }
  }

}

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,
  );
}
///
/// @author akira ohmachi
/// @copyright ao-system, Inc.
/// @date 2023-01-27
///
library;

import 'package:flutter/material.dart';

import 'package:bingoonline/model.dart';
import 'package:bingoonline/theme_color.dart';

class ProgressTable {
  late ThemeColor _themeColor;

  Widget table(BuildContext context, ThemeColor themeColor) {
    _themeColor = themeColor;

    // BINGOヘッダー + 数字セル
    final List<Widget> cells = [
      ...['B', 'I', 'N', 'G', 'O'].map((str) => cellProgressBingo(str)),
      ...[
        1, 16, 31, 46, 61,
        2, 17, 32, 47, 62,
        3, 18, 33, 48, 63,
        4, 19, 34, 49, 64,
        5, 20, 35, 50, 65,
        6, 21, 36, 51, 66,
        7, 22, 37, 52, 67,
        8, 23, 38, 53, 68,
        9, 24, 39, 54, 69,
        10, 25, 40, 55, 70,
        11, 26, 41, 56, 71,
        12, 27, 42, 57, 72,
        13, 28, 43, 58, 73,
        14, 29, 44, 59, 74,
        15, 30, 45, 60, 75,
      ].map((num) => cellProgress(num)),
    ];

    return GridView(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
        maxCrossAxisExtent: MediaQuery.of(context).size.width / 5,
        mainAxisSpacing: 4,
        crossAxisSpacing: 4,
        childAspectRatio: 2,
      ),
      children: cells,
    );
  }

  Widget cellProgressBingo(String str) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 8),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(36),
      ),
      child: Center(
        child: Text(str, style: const TextStyle(color: Colors.white)),
      ),
    );
  }

  Widget cellProgress(int num) {
    Color bgColor = _themeColor.progressCellColor0;
    if (Model.ballHistoryContain(num)) {
      bgColor = _themeColor.progressCellColor1;
      if (Model.ballHistoryIsLast(num)) {
        bgColor = _themeColor.progressCellColor2;
      }
    }
    return Container(
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(36),
      ),
      child: Center(
        child: Text(
          num.toString(),
          style: const TextStyle(fontSize: 16),
        ),
      ),
    );
  }
}
///
/// @author akira ohmachi
/// @copyright ao-system, Inc.
/// @date 2023-01-27
///
library;

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

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

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

class _SettingPageState extends State<SettingPage> {
  late AdManager _adManager;
  double _machineVolume = 1.0;
  late List<TtsOption> _ttsVoices;
  bool _ttsEnabled = true;
  String _ttsVoiceId = '';
  double _ttsVolume = 1.0;
  late ThemeColor _themeColor;
  int _themeNumber = 0;
  String _languageCode = '';
  bool _isReady = false;
  bool _isFirst = true;
  //AdUmpState
  late final UmpConsentController _adUmp;
  AdUmpState _adUmpState = AdUmpState.initial;
  //

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

  void _initState() async {
    super.initState();
    _adManager = AdManager();
    _machineVolume = Model.machineVolume;
    _ttsEnabled = Model.ttsEnabled;
    _ttsVoiceId = Model.ttsVoiceId;
    _ttsVolume = Model.ttsVolume;
    _themeNumber = Model.themeNumber;
    _languageCode = Model.languageCode;
    //speech
    await TextToSpeech.getInstance();
    _ttsVoices = TextToSpeech.ttsVoices;
    TextToSpeech.setVolume(_ttsVolume);
    TextToSpeech.setTtsVoiceId(_ttsVoiceId);
    //
    _adUmp = UmpConsentController();
    _refreshConsentInfo();
    //
    setState(() {
      _isReady = true;
    });
  }

  @override
  void dispose() {
    _adManager.dispose();
    super.dispose();
  }

  Future<void> _refreshConsentInfo() async {
    _adUmpState = await _adUmp.updateConsentInfo(current: _adUmpState);
    if (mounted) {
      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}')),
      );
    }
  }

  void _onApply() async {
    FocusScope.of(context).unfocus();
    await Model.setMachineVolume(_machineVolume);
    await Model.setTtsEnabled(_ttsEnabled);
    await Model.setTtsVolume(_ttsVolume);
    await Model.setTtsVoiceId(_ttsVoiceId);
    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 SafeArea(
      top: false,
      left: false,
      right: false,
      bottom: true,
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          elevation: 0,
          leading: IconButton(
            icon: const Icon(Icons.close),
            onPressed: () {
              Navigator.of(context).pop(false);
            },
          ),
          title: Text(l.setting),
          actions: [
            IconButton(
              icon: const Icon(Icons.check),
              onPressed: _onApply
            ) ,
          ],
        ),
        body: Column(children:[
          Expanded(
            child: GestureDetector(
              onTap: () => FocusScope.of(context).unfocus(),  //背景タップでキーボードを仕舞う
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.only(left: 8, right: 8, top: 8, bottom: 100),
                  child: Column(
                    children: [
                      _buildVolumeSection(l),
                      _buildSpeechSettings(l),
                      _buildThemeSection(l),
                      _buildLanguage(l),
                      _buildCmpSection(l),
                      _buildUsageSection(l),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ]),
        bottomNavigationBar: AdBannerWidget(adManager: _adManager),
      ),
    );
  }

  Widget _buildVolumeSection(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: 12, bottom: 4),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(l.machineVolume),
                Row(
                  children: [
                    Text(
                      _machineVolume.toStringAsFixed(1),
                      textAlign: TextAlign.right,
                    ),
                    Expanded(
                      child: Slider(
                        value: _machineVolume,
                        min: 0.0,
                        max: 1.0,
                        divisions: 10,
                        label: _machineVolume.toStringAsFixed(1),
                        onChanged: (value) {
                          setState(() {
                            _machineVolume = value;
                          });
                        },
                      ),
                    ),
                  ],
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

  Widget _buildSpeechSettings(AppLocalizations l) {
    if (_ttsVoices.isEmpty) {
      return SizedBox.shrink();
    }
    final l = AppLocalizations.of(context)!;
    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 _buildThemeSection(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: 4),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ListTile(
              title: Text(
                l.theme,
                style: Theme.of(context).textTheme.bodyMedium,
              ),
              contentPadding: EdgeInsets.zero,
              trailing: 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) {
                    return;
                  }
                  setState(() {
                    _themeNumber = value;
                  });
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLanguage(AppLocalizations l) {
    final Map<String,String> languageNames = {
      'en': 'English',
      'bg': 'Bulgarian',
      'cs': 'Čeština',
      'da': 'Dansk',
      'de': 'Deutsch',
      'el': 'Ελληνικά',
      'es': 'Español',
      'et': 'Eesti',
      'fi': 'Suomi',
      'fr': 'Français',
      'hu': 'Magyar',
      'id': 'Indonesia',
      'it': 'Italiano',
      'ja': '日本語',
      'ko': '한국어',
      'lt': 'Lietuvių',
      'lv': 'Latviešu',
      'nb': 'Norsk Bokmål',
      'nl': 'Nederlands',
      'no': 'Norsk',
      'pl': 'Polski',
      'pt': 'Português',
      'ro': 'Română',
      'ru': 'Русский',
      'sk': 'Slovenčina',
      'sv': 'Svenska',
      'th': 'ไทย',
      'tr': 'Türkçe',
      'uk': 'Українська',
      'vi': 'Tiếng Việt',
      'zh': '中文',
    };
    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: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ListTile(
              title: Text(l.language,style: Theme.of(context).textTheme.bodyMedium),
              contentPadding: const EdgeInsets.symmetric(horizontal: 0),
              trailing: DropdownButton<String?>(
                value: _languageCode.isEmpty ? null : _languageCode,
                items: [
                  DropdownMenuItem<String?>(
                    value: null,
                    child: const Text('Default'),
                  ),
                  ...languageNames.entries.map(
                        (entry) => DropdownMenuItem<String?>(
                      value: entry.key,
                      child: Text(entry.value),
                    ),
                  ),
                ],
                onChanged: (String? value) {
                  setState(() {
                    _languageCode = value ?? '';
                  });
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCmpSection(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),
                        ),
                      ]
                    )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildUsageSection(AppLocalizations l) {
    final noteStyle = Theme.of(context).textTheme.bodySmall;
    return SizedBox(
        width: double.infinity,
        child: 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: [
                Text(l.usage1, style: noteStyle),
                const SizedBox(height: 16),
                Text(l.usage2, style: noteStyle),
                const SizedBox(height: 16),
                Text(l.usage3, style: noteStyle),
                const SizedBox(height: 16),
                Text(l.usage4, style: noteStyle),
              ],
            ),
          ),
        )
    );
  }

}
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';
}

//外部からの利用方法
//await TextToSpeech.getInstance();
//_ttsVoices = TextToSpeech.ttsVoices;
//TextToSpeech.setTtsVoiceId(_ttsVoiceId);
//etc.
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 void setTtsVoiceId(String newTtsVoiceId) {
    final exists = ttsVoices.any((o) => o.id == newTtsVoiceId);
    if (exists) {
      ttsVoiceId = newTtsVoiceId;
    } else {
      ttsVoiceId = ttsVoices.first.id;
    }
  }

  //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> 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';

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;
    }
  }

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

  //machine
  Color get machineForeColor => _isLight ? Colors.green[500]! : Colors.greenAccent[700]!;
  Color get machineMovieBackColor => _isLight ? Color.fromRGBO(40,245,146,1) : Colors.green[900]!;
  //card
  Color get cardInitColor => _isLight ? Colors.orange[500]! : Colors.orangeAccent[700]!;
  Color get cardBackColor => _isLight ? Color.fromRGBO(197,172,119,1) : Color.fromRGBO(67, 52, 29, 1.0);
  Color get cardFrameColor => _isLight ? Colors.amber[500]! : Colors.lime[900]!;
  Color get cardCellColor => _isLight ? Colors.white : Colors.grey[800]!;
  //progress
  Color get progressMachineFrameColor => _isLight ? Color.fromRGBO(40,245,146, 1.0) : Colors.green[800]!;
  Color get progressCardFrameColor => _isLight ? Colors.brown[300]! : Colors.grey[900]!;
  Color get progressCellColor0 => _isLight ? Colors.white : Colors.grey[800]!;
  Color get progressCellColor1 => _isLight ? Colors.yellow : Colors.lime[900]!;
  Color get progressCellColor2 => _isLight ? Colors.orange : Colors.orange[900]!;
  //setting page
  Color get backColor => _isLight ? Colors.grey[300]! : 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;
    }
  }
}