import 'package:checker/db.dart';
import 'package:checker/strings.dart';
import 'package:flutter/material.dart';
import 'package:checker/screens/splash.dart';
import 'package:flutter/services.dart';

const platform = const MethodChannel('com.dinect.checker/instance_id');

main() {

  platform.invokeMethod('getFlavor').then((flavor) {
    platform.invokeMethod('getAppTitle').then((title) {

      String app = flavor;  // dinect, autobonus
      String appName= title;  // Dinect, Dinect (INT), Autobonus

      SqliteHelper helper = new SqliteHelper();

      helper.open().then((_) {
        helper.getLocale().then((locale) {
          if (locale == null) {
            initWithSystemValue(app, appName, locale, helper);
          } else {
            start(app, appName, locale, helper);
          }
        });
      });
    });
  });
}

initWithSystemValue(String app, String name, String locale, SqliteHelper helper) {
  helper.getSettings(false).then((settings) {
    if (settings.isEmpty) {
      createSettingsTable(app, name, helper);
    } else {
      start(app, name, locale, helper);
    }
  });
}

createSettingsTable(String app, String name, SqliteHelper helper) {
  platform.invokeMethod('getLocale').then((locale) {
    platform.invokeMethod('getCurrency').then((currency) {
      helper.createAppInfo(currency, locale).then((_) {
        start(app, name, locale, helper);
      });
    });
  });
}

start(String app, String name, String locale, SqliteHelper helper) {
  StringsLocalization.load(locale).then((_) {
    runApp(new Checker(app, name, helper));
  });
}

class Checker extends StatefulWidget {

  final SqliteHelper helper;
  final String app;
  final String appName;

  Checker(this.app, this.appName, this.helper);

  @override
  State<StatefulWidget> createState() => new CheckerState(
    this.app,
    this.appName,
    this.helper);
}

class CheckerState extends State<Checker> {

  SqliteHelper helper;
  String app;
  String appName;

  CheckerState(this.app, this.appName, this.helper);

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
        title: appName,
        home: new SplashScreen(helper, app)
    );
  }
}
