import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shorebird_code_push/shorebird_code_push.dart';
import 'package:restart_app/restart_app.dart';


void main() {
  runApp(const MyApp());
}

class ShorebirdPatch extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ShorebirdPatchState();
}

enum PatchState {
  loading,
  noUpdate,
  updateReady;
}

class _ShorebirdPatchState extends State<ShorebirdPatch> {
  final shorebird = ShorebirdCodePush();
  late Timer timer;
  PatchState patchState = PatchState.noUpdate;

  @override
  void initState() {
    timer = Timer.periodic(const Duration(minutes: 5), (timer) async {
      if (!shorebird.isShorebirdAvailable()) {
        timer.cancel();
        return;
      }
      if (!await shorebird.isNewPatchAvailableForDownload()) {
        setState(() {
          patchState = PatchState.noUpdate;
        });
        return;
      }
      final download = shorebird.downloadUpdateIfAvailable();
      setState(() {
        patchState = PatchState.loading;
      });
      await download;
      if (await shorebird.isNewPatchReadyToInstall()) {
        setState(() {
          patchState = PatchState.updateReady;
        });
        return;
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    switch (patchState) {
      case PatchState.loading:
        return const SizedBox.square(dimension: 48, child: Center(child: CircularProgressIndicator()));
      case PatchState.noUpdate:
        return const SizedBox.shrink();
      case PatchState.updateReady:
        return InkWell(
          child: const SizedBox.square(dimension: 48, child: Icon(Icons.update, size: 24)),
          onTap: () {
            Restart.restartApp();
          },
        );
    }
  }
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: String.fromEnvironment('TITLE')),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
        actions: [ShorebirdPatch()],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
              // 'You have times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
