426 lines
13 KiB
Dart

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_beacon/flutter_beacon.dart';
import 'package:get/get.dart';
import 'package:manager_api/api.dart';
import 'package:mymuseum_visitapp/Components/CustomAppBar.dart';
import 'package:mymuseum_visitapp/Components/ScannerBouton.dart';
import 'package:mymuseum_visitapp/Helpers/requirement_state_controller.dart';
import 'package:mymuseum_visitapp/Helpers/translationHelper.dart';
import 'package:mymuseum_visitapp/Models/beaconSection.dart';
import 'package:mymuseum_visitapp/Models/visitContext.dart';
import 'package:mymuseum_visitapp/Screens/Visit/beaconArticleFound.dart';
import 'package:mymuseum_visitapp/app_context.dart';
import 'package:mymuseum_visitapp/constants.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'components/body.dart';
class VisitPage extends StatefulWidget {
const VisitPage({Key? key, required this.configurationId}) : super(key: key);
final String configurationId;
@override
State<VisitPage> createState() => _VisitPageState();
}
class _VisitPageState extends State<VisitPage> with WidgetsBindingObserver {
ConfigurationDTO? configuration;
// Beacon specific
final controller = Get.find<RequirementStateController>();
StreamSubscription<BluetoothState>? _streamBluetooth;
StreamSubscription<RangingResult>? _streamRanging;
final _regionBeacons = <Region, List<Beacon>>{};
final _beacons = <Beacon>[];
bool _isDialogShowing = false;
StreamSubscription? listener;
@override
void initState() {
WidgetsBinding.instance.addObserver(this);
super.initState();
listeningState();
}
listeningState() async {
print('Listening to bluetooth state');
_streamBluetooth = flutterBeacon
.bluetoothStateChanged()
.listen((BluetoothState state) async {
controller.updateBluetoothState(state);
await checkAllRequirements();
});
}
checkAllRequirements() async {
final bluetoothState = await flutterBeacon.bluetoothState;
controller.updateBluetoothState(bluetoothState);
print('BLUETOOTH $bluetoothState');
final authorizationStatus = await flutterBeacon.authorizationStatus;
controller.updateAuthorizationStatus(authorizationStatus);
print('AUTHORIZATION $authorizationStatus');
final locationServiceEnabled =
await flutterBeacon.checkLocationServicesIfEnabled;
controller.updateLocationService(locationServiceEnabled);
print('LOCATION SERVICE $locationServiceEnabled');
if (controller.bluetoothEnabled &&
controller.authorizationStatusOk &&
controller.locationServiceEnabled) {
print('STATE READY');
//if (currentIndex == 0) {
print('SCANNING');
//controller.startScanning();
var status = await Permission.bluetoothScan.status;
if (status.isDenied) {
print("IS DENIIIED");
// We didn't ask for permission yet or the permission has been denied before but not permanently.
}
// You can request multiple permissions at once.
Map<Permission, PermissionStatus> statuses = await [
Permission.bluetoothScan,
Permission.bluetoothConnect,
].request();
print(statuses[Permission.bluetoothScan]);
print(statuses[Permission.bluetoothConnect]);
print(status);
/*controller.startStream.listen((flag) {
if (flag == true) {
initScanBeacon();
}
});*/
/*} else {
print('BROADCASTING');
controller.startBroadcasting();
}*/
} else {
print('STATE NOT READY');
controller.pauseScanning();
}
}
initScanBeacon(VisitAppContext visitAppContext) async {
await flutterBeacon.initializeScanning;
if (!controller.authorizationStatusOk ||
!controller.locationServiceEnabled ||
!controller.bluetoothEnabled) {
print(
'RETURNED, authorizationStatusOk=${controller.authorizationStatusOk}, '
'locationServiceEnabled=${controller.locationServiceEnabled}, '
'bluetoothEnabled=${controller.bluetoothEnabled}');
return;
}
final regions = <Region>[
Region(
identifier: 'MyMuseumB'
),
];
if (_streamRanging != null) {
if (_streamRanging!.isPaused) {
_streamRanging?.resume();
return;
}
}
_streamRanging =
flutterBeacon.ranging(regions).listen((RangingResult result) {
//print(result);
if (mounted) {
//print("visitAppContext");
//print(visitAppContext);
//print(visitAppContext!.beaconSections);
if(result.beacons.isNotEmpty) {
print(result);
print(result.beacons.map((b) => b.macAddress));
print(visitAppContext.beaconSections!.map((bb) => bb!.macAddress));
var beaconList = visitAppContext.beaconSections!.where((bs) => result.beacons.any((element) => element.macAddress == bs!.macAddress));
if(beaconList.isNotEmpty)
{
print("GOT ONE BEACON THAT I KNOOOOOOOOW");
print(beaconList);
// TODO SORT BY COMPARE
if(!_isDialogShowing) {
_onBeaconFound(visitAppContext, beaconList.first!);
} else {
print("Already showing làà");
}
//print("BEFORE SNACKBAR");
/*ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('BEACON - ${result.beacons.first.macAddress} - ${result.beacons.first.accuracy} - ${result.beacons.first.proximity.name}'), backgroundColor: kBlue2),
);
print("AFTER SNACKBAR");*/
}
}
//setState(() {
/*_regionBeacons[result.region] = result.beacons;
_beacons.clear();
_regionBeacons.values.forEach((list) {
_beacons.addAll(list);
});
_beacons.sort(_compareParameters);*/
//});
}
});
}
/*pauseScanBeacon() async {
_streamRanging?.pause();
if (_beacons.isNotEmpty) {
setState(() {
_beacons.clear();
});
}
}*/
int _compareParameters(Beacon a, Beacon b) {
int compare = a.proximityUUID.compareTo(b.proximityUUID);
if (compare == 0) {
compare = a.major.compareTo(b.major);
}
if (compare == 0) {
compare = a.minor.compareTo(b.minor);
}
return compare;
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) async {
print('AppLifecycleState = $state');
if (state == AppLifecycleState.resumed) {
if (_streamBluetooth != null) {
if (_streamBluetooth!.isPaused) {
_streamBluetooth?.resume();
}
}
await checkAllRequirements();
} else if (state == AppLifecycleState.paused) {
_streamBluetooth?.pause();
}
}
@override
/*Widget build(BuildContext context) {
return new WillPopScope(
onWillPop: () async => false,
child: new Scaffold(
appBar: new AppBar(
title: new Text("data"),
leading: new IconButton(
icon: new Icon(Icons.ac_unit),
onPressed: () => Navigator.of(context).pop(),
),
),
),
);
}*/
void _onBeaconFound(VisitAppContext visitAppContext, BeaconSection beaconSection) {
_isDialogShowing = true;
showDialog(
barrierDismissible: false,
builder: (BuildContext context) => AlertDialog(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10.0))
),
content: BeaconArticleFound(beaconSection: beaconSection),
actions: <Widget>[
TextButton(
child: Text("CANCEL"),
onPressed: () {
_isDialogShowing = false; // set it `false` since dialog is closed
Navigator.of(context).pop();
},
)
],
contentPadding: EdgeInsets.zero,
), context: context
);
/*Future.delayed(const Duration(seconds: 6), () {
Navigator.pop(context); //pop dialog
_isDialogShowing = false;
});*/
}
@override
void onDispose() {
print("DISPOSE VISIT PAGE");
super.dispose();
}
Widget build(BuildContext context) {
final appContext = Provider.of<AppContext>(context);
VisitAppContext visitAppContext = appContext.getContext();
configuration = visitAppContext.configuration;
//if(visitAppContext.isBeaconEnabled) {
listener = controller.startStream.listen((flag) async {
print(flag);
if (flag == true) {
print("FIIIIIIREEEE ---------------");
await initScanBeacon(visitAppContext);
controller.startScanning();
}
});
//}
return /*WillPopScope(
child:*/ Scaffold(
appBar: CustomAppBar(
title: TranslationHelper.get(configuration!.title, appContext),
isHomeButton: true,
),
backgroundColor: kBackgroundGrey,
body: Body(configurationId: configuration!.id), // TODO handle error..
floatingActionButton: Stack(
children: [
visitAppContext.beaconSections!.where((bs) => bs!.configurationId == visitAppContext.configuration!.id).isNotEmpty ? Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.only(right: 90, bottom: 1),
child: Container(
height: 65.0,
width: 65.0,
child: FittedBox(
child: FloatingActionButton(
heroTag: "beacon",
onPressed: () {
setState(() {
if(!visitAppContext.isBeaconEnabled) {
print("Start Scan");
controller.startScanning();
listener!.resume();
visitAppContext.isBeaconEnabled = true;
appContext.setContext(visitAppContext);
} else {
print("Pause Scan");
controller.pauseScanning(); // PAUSE OR DISPOSE ?
//controller.dispose(); // PAUSE OR DISPOSE ?
print(controller.pauseStream);
listener!.cancel();
listener!.pause();
//controller.removeListenerId(listener.i, () { });
visitAppContext.isBeaconEnabled = false;
appContext.setContext(visitAppContext);
}
});
},
tooltip: 'Beacon',
backgroundColor: visitAppContext.isBeaconEnabled ? kBlue1 : Colors.grey,
child: const Icon(Icons.my_location),
),
),
),
),
) : const SizedBox(),
Align(
alignment: Alignment.bottomRight,
child: ScannerBouton(appContext: appContext),
),
],
),/*Padding(
padding: const EdgeInsets.only(right: 10),
child: Row(
children: [
Container(
height: 65.0,
width: 65.0,
child: FittedBox(
child: FloatingActionButton(
heroTag: "beacon",
onPressed: () {},
tooltip: 'Beacon',
backgroundColor: kBlue1,
child: const Icon(Icons.qr_code_scanner),
),
),
),
ScannerBouton(appContext: appContext),
],
),
),*/
);//,
//onWillPop: () async => false,
//);
}
handleOpenLocationSettings() async {
if (Platform.isAndroid) {
await flutterBeacon.openLocationSettings;
} else if (Platform.isIOS) {
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Location Services Off'),
content: Text(
'Please enable Location Services on Settings > Privacy > Location Services.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('OK'),
),
],
);
},
);
}
}
handleOpenBluetooth() async {
if (Platform.isAndroid) {
try {
await flutterBeacon.openBluetoothSettings;
} on PlatformException catch (e) {
print(e);
}
} else if (Platform.isIOS) {
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Bluetooth is Off'),
content: Text('Please enable Bluetooth on Settings > Bluetooth.'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('OK'),
),
],
);
},
);
}
}
}