/*

Copyright 2019 fuwa

This file is part of CyberWOW.

CyberWOW is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

CyberWOW is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with CyberWOW.  If not, see <https://www.gnu.org/licenses/>.

*/

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

import 'dart:io';
import 'dart:async';

import 'state.dart';
import 'config.dart';
import 'controller/loading.dart';
import 'controller/syncing.dart';
import 'widget/loading.dart';
import 'widget/blank.dart';
import 'widget/syncing.dart';
import 'widget/synced.dart';
import 'widget/resyncing.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp
    (
      title: 'CyberWOW',
      theme: ThemeData
      (
        primarySwatch: Colors.purple,
      ),
      home: MyHomePage(title: 'CyberWOW'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver
{
  int _counter = 0;
  // AppState _state = LoadingState("init...");

  AppState _state;
  AppLifecycleState _notification = AppLifecycleState.resumed;

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // print('app cycle: ${state}');
    setState(() { _notification = state; });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  void _setState(AppState newState) {
    setState
    (
      () => _state = newState
    );
  }

  AppLifecycleState _getNotification() {
    return _notification;
  }

  AppState _getState() {
    return _state;
  }


  void _updateLoading(LoadingState state, String msg) {
    print('updateLoading: ' + msg);
  }

  Future<void> buildStateMachine(BlankState _blankState) async {
    final loadingText = config.splash;
    LoadingState _loadingState = await _blankState.next(loadingText);

    final binName = config.outputBin;
    final resourcePath = 'native/output/' + arch + '/' + binName;
    final bundle = DefaultAssetBundle.of(context);
    final loading = deployBinary(bundle, resourcePath, binName);

    SyncingState _syncingState = await _loadingState.next(loading, '');

    final syncing = runBinary(binName).asBroadcastStream();

    SyncedState _syncedState = await _syncingState.next(syncing);
    await _syncedState.next();

    var validState = true;
    while (validState) {
      await _getState().use
      (
        (s) => () => validState = false,
        (s) => () => validState = false,
        (s) => () => validState = false,
        (s) => s.next(),
        (s) => s.next(),
      );
    }
  }

  @override
  void initState() {
    super.initState();
    print("MyHomePageState initState");

    WidgetsBinding.instance.addObserver(this);

    SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]);

    BlankState _blankState = BlankState(_setState, _getNotification);
    _state = _blankState;

    buildStateMachine(_blankState);
  }

  Future<bool> _exitApp(BuildContext context) async {
    print("MyHomePageState _exitApp");
    exit(0);
  }

  @override
  Widget build(BuildContext context) {
    return new WillPopScope
    (
      onWillPop: () => _exitApp(context),
      child: _state.use
      (
        (s) => buildBlank(context, s),
        (s) => buildLoading(context, s),
        (s) => buildSyncing(context, s),
        (s) => buildSynced(context, s),
        (s) => buildReSyncing(context, s),
      ),
    );
  }
}
