import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shinewash_employee/screens/home_page.dart';
import 'package:shinewash_employee/screens/sign_in.dart';

import 'api/api.dart';

Future<void> main() {
  ErrorWidget.builder = (FlutterErrorDetails details) {
    bool inDebug = false;
    assert(() {
      inDebug = true;
      return true;
    }());
    // In debug mode, use the normal error widget which shows
    // the error message:
    if (inDebug) return ErrorWidget(details.exception);
    // In release builds, show a yellow-on-blue message instead:
    return Container(
      alignment: Alignment.center,
      child: Text(
        'Error!',
        style: TextStyle(color: Colors.yellow),
        textDirection: TextDirection.ltr,
      ),
    );
  };
  //for login

  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  // This widget is the root of your application.

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

class _MyAppState extends State<MyApp> {
  var appId;
  bool _isLoggedIn = false;
  @override
  void initState() {
    super.initState();
    OneSignal.shared.setLogLevel(OSLogLevel.verbose, OSLogLevel.none);
    getOneSignalRequest();
    checkLogin();
  }

  Future<void> checkLogin() async {
    SharedPreferences localStorage = await SharedPreferences.getInstance();
    var user = localStorage.getString('user');
    if (user != null) {
      setState(() {
        _isLoggedIn = true;
      });
    } else {
      setState(() {
        _isLoggedIn = false;
      });
    }
  }

  Future<void> getOneSignalRequest() async {
    //one signal mate
    await OneSignal.shared.setRequiresUserPrivacyConsent(true);
    var settingApi = await CallApi().getData('setting');
    var bodyy = json.decode(settingApi.body);
    Map theDataa = bodyy['data'];
    appId = theDataa['coworker_app_id'];
    OneSignal.shared.consentGranted(true);
    OneSignal.shared.init("$appId");

    OneSignal.shared.setLogLevel(OSLogLevel.verbose, OSLogLevel.none);

    OneSignal.shared.init("$appId", iOSSettings: {
      OSiOSSettings.autoPrompt: false,
      OSiOSSettings.inAppLaunchUrl: false
    });
    OneSignal.shared
        .setInFocusDisplayType(OSNotificationDisplayType.notification);

// The promptForPushNotificationsWithUserResponse function will show the iOS push notification prompt. We recommend removing the following code and instead using an In-App Message to prompt for notification permission
    await OneSignal.shared
        .promptUserForPushNotificationPermission(fallbackToSettings: true);

    var status = await OneSignal.shared.getPermissionSubscriptionState();

    Timer(Duration(seconds: 2), () async {
      var playerId = status.subscriptionStatus.userId;
      print('playerId is $playerId');
    });
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'ShineWash Employee',
      theme: ThemeData(
        primaryColor: Color(0xFF6B48FF),
        scaffoldBackgroundColor: Colors.white,
        dividerColor: Colors.transparent,
      ),
      home: _isLoggedIn ? HomePage() : SignIn(),
    );
  }
}
