import 'dart:io';

import 'package:boilerplate/core/di/injection_init.dart';
import 'package:boilerplate/core/enum/flavor.dart';
import 'package:boilerplate/domain/entities/flavor/flavor_data.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../../widgets/ipm_dialog.dart';

class AppUpdated extends StatefulWidget {
  final Widget child;

  AppUpdated({Key? key, required this.child}) : super(key: key);

  @override
  State<AppUpdated> createState() => _AppUpdatedState();
}

class _AppUpdatedState extends State<AppUpdated> {
  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      // _checkUpdate();
    });
  }

  _checkUpdate() async {
    final flavorSetting = getIt.get<AppFlavorData>();
    final info = await PackageInfo.fromPlatform();
    final versionName = info.version;
    final versionCode = info.buildNumber;

    FirebaseFirestore.instance
        .collection('app_version')
        .doc(flavorSetting.flavorName.value)
        .get()
        .then((value) async {
      if (value['version'] != null &&
          value['code'] != null &&
          value['update_url'] != null) {
        final int v = int.parse(value['version'].replaceAll('.', ''));
        final int c = int.parse(value['code']);
        final String url = value['update_url'];
        final int currentV = int.parse(versionName.replaceAll('.', ''));
        final int currentC = int.parse(versionCode);

        if (currentV >= v && currentC >= c) {
          return;
        }

        final result = await showDialog(
          context: context,
          builder: (context) {
            return IPMDialog(
              type: IPMDialogType.comfirm,
              message: 'แอพพลิเคชันมีเวอร์ที่ใหม่กว่ากรุณาอัพเดต',
            );
          },
        );

        if (result) {
          if (flavorSetting.flavorName != Flavors.prd) {
            launchUrlString(
              url,
              mode: LaunchMode.externalApplication,
            );
          }
        } else {
          exit(0);
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}
