
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:http/http.dart' as http; //for making request
import 'package:get/get.dart';
import 'dart:async'; //for asynchronous features
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

import 'Helper/Constants/Apiconstants.dart';
import 'View/Home/Homeview.dart';


const AndroidNotificationChannel channel = AndroidNotificationChannel(
    'Nearlexpress Business', // id
    'Nearlexpress Business Notifications', // title
    importance: Importance.high,
    playSound: true);
   bool? canUpadteNew;

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();


void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp();
  // FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  // SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(statusBarColor: Colors.white,));
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
  ApiConstants.describeUrl = ApiConstants.describeUrlDev;
  ApiConstants.login = ApiConstants.loginDev;
  ApiConstants.configUrl = ApiConstants.configUrlDev;
  ApiConstants.user = ApiConstants.userDev;
  ApiConstants.getCustomerByTenantId = ApiConstants.getCustomerByTenantIdDev;
  ApiConstants.getDeliveries = ApiConstants.getDeliveriesDev;
  ApiConstants.notifyUrl = ApiConstants.notifyUrlDev;
  ApiConstants.updateOrderStatus = ApiConstants.updateOrderStatusDev;
  ApiConstants.getOrderSummary = ApiConstants.getOrderSummaryDev;
  ApiConstants.getTenantInfo = ApiConstants.getTenantInfoDev;
  ApiConstants.appLocations = ApiConstants.appLocationsDev;
  ApiConstants.getPartnerInfo = ApiConstants.getPartnerInfoDev;
  ApiConstants.appCategory = ApiConstants.appCategoryDev;
  ApiConstants.createTenantUser = ApiConstants.createTenantUserDev;
  ApiConstants.createCustomer = ApiConstants.createCustomerDev;
  ApiConstants.createDeliveryAddress = ApiConstants.createDeliveryAddressDev;
  ApiConstants.getCustomerAddress = ApiConstants.getCustomerAddressDev;
  ApiConstants.getTenantLocationById = ApiConstants.getTenantLocationByIdDev;
  ApiConstants.getLocationsById = ApiConstants.getLocationsByIdDev;
  ApiConstants.adminToken = ApiConstants.adminTokenDev;
  ApiConstants.getTenantPricing = ApiConstants.getTenantPricingDev;
  ApiConstants.createOrder = ApiConstants.createOrderDev;
  ApiConstants.getOrders = ApiConstants.getOrdersDev;
  ApiConstants.getLocationById = ApiConstants.getLocationByIdDev;
  ApiConstants.updateLocation = ApiConstants.updateLocationDev;
  ApiConstants.createLocation = ApiConstants.createLocationDev;
  ApiConstants.getStaffs = ApiConstants.getStaffsDev;
  ApiConstants.createStaff = ApiConstants.createStaffDev;
  ApiConstants.updateStaff = ApiConstants.updateStaffDev;
  ApiConstants.userUpdate = ApiConstants.userUpdateDev;
  ApiConstants.getCustomerSearchByTenantId = ApiConstants.getCustomerSearchByTenantIdDev;
  ApiConstants.createDelivery = ApiConstants.createDeliveryLive;

  runApp(MyApp());
}



// Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {

//   print("Handling a background message: ${message.messageId}");
// }
class MyApp extends StatelessWidget {
  static final GlobalKey<NavigatorState> mNavigationState =
      GlobalKey<NavigatorState>();

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
        title: 'Nearlexpress Business',
        debugShowCheckedModeBanner: false,
        color: Colors.white,
        navigatorKey: mNavigationState,

        theme: ThemeData(
          // scaffoldBackgroundColor: Colors.white,
          // accentColor: primaryColor,
          fontFamily: 'Lato',
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home:
            // Container()
            MyHomePageOne());
  }
}

class MyHomePageOne extends StatefulWidget {
  const MyHomePageOne({Key? key}) : super(key: key);

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

class MyHomePageOneState extends State<MyHomePageOne> {
  // FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;
  String notificationOrderId = '';
  // RemoteMessage? messageNotification;
  late StreamSubscription internetSubscription;
  // final status = AppVersionChecker();

  @override
  void initState() {
    getLocal();
    // fcmToken();
    checkToken();
    print('LocalNotificationService before');
    // LocalNotificationService.initialize(context);
    print('LocalNotificationService after');
    super.initState();
    //checkVersion();

    // firebaseMethod();

  }
  // checkVersion() async {
  //   status.checkUpdate().then((value) {
  //     print(value.canUpdate); //return true if update is available
  //     print(value.currentVersion); //return current app version
  //     print(value.newVersion); //return the new app version
  //     print(value.appURL); //return the app url
  //     print(value.errorMessage);
  //     List<String>? versionParts = value.currentVersion.split('.');
  //     int majorVersion = int.parse(versionParts[0]);
  //     int minorVersion = int.parse(versionParts[1]);
  //     print('majorVersionappversion $majorVersion');
  //     print('minorVersionappversion $minorVersion');
  //     if(value.canUpdate){
  //       Navigator.push(
  //           context,
  //           MaterialPageRoute(
  //               builder: (BuildContext context) => UpdateAppPage(mCurrentVersion: value.currentVersion.toString(),mUpdateVersion: value.newVersion.toString(), minorVersion: minorVersion, majorVersion: majorVersion,)));
  //     }//return error message if found else it will return null
  //   });
  // }
  //
  // fcmToken() async {
  //
  //   SharedPreferences prefs = await SharedPreferences.getInstance();
  //   // firebaseMessaging.getToken().then((token) {
  //     print("firebase token======$token");
  //
  //     prefs.setString('fcmToken', token!);
  //
  //   });
  // }

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

  bool hasInterNetConnection = false;


  String? country;
  String? country2;

  getLocal() async {
    var url = Uri.http('ip-api.com', 'json');
    try {
      http.get(url).then((value) async {
        print('country Code');
        print(json.decode(value.body)['countryCode'].toString());
        print('City');
        print(json.decode(value.body)['city'].toString());
        country = json.decode(value.body)['countryCode'].toString();
        print("fcountry$country");
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.clear();
        prefs.setString('location_Country', country!);
        prefs.setString('MainCity', json.decode(value.body)['city'].toString());
        prefs.setString('location_CountryCode', country!);

          country2 = prefs.getString('location_Country');

      });
    } catch (err) {
      //handleError
      print('erroe in getLocal');
    }
  }

  bool noConnection = false;
  // FirebaseMessaging firebaseMessaging = FirebaseMessaging();
  String? token;
  String? tenantEmail;
  String? tenantContact;
  int? moduleId;
  int? tenantId;
  List moduleResult = [];
  List locationResult = [];

  checkToken() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    setState(()  {
      token = prefs.getString('token')!;
      moduleId = prefs.getInt('moduleId')!;
      tenantId = prefs.getInt('tenantId')!;
      tenantEmail = prefs.getString('tenantEmail')??'';
      tenantContact = prefs.getString('tenantContact');

      if (token != null && tenantId != 0) {

        final listq = json.decode(prefs.getString('mylocation')!);
        locationResult.addAll(listq);
        prefs.setInt('locationId', locationResult[0]['locationid']);
        prefs.setString('locationName', locationResult[0]['locationname']);

      }

      // moduleResult = json.decode(prefs.getString('mymodules'));
    });
    print(tenantId);
  }

  @override
  Widget build(BuildContext context) {

    return HomeView(
            selectedIndex: 0,
          );
  }
}


