Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'package:flutter/material.dart';
- import 'package:google_maps_flutter/google_maps_flutter.dart';
- import 'dart:async';
- import 'dart:math';
- import 'package:soundscape/models/pages/map_screen/buttons_top_main_page.dart';
- import 'package:soundscape/models/pages/map_screen/buttons_bottom_main_page.dart';
- import "package:soundscape/models/shared/bottom_nav_bar.dart";
- import 'package:soundscape/shared/managers/markers_manager.dart';
- import 'package:soundscape/shared/managers/music_manager.dart';
- import "package:soundscape/shared/managers/steam_music_manager.dart";
- import "package:soundscape/shared/managers/polygons_manager.dart";
- import 'package:provider/provider.dart';
- import 'package:soundscape/shared/providers/location_provider.dart';
- import 'package:soundscape/shared/providers/parametre_provider.dart';
- import 'package:soundscape/shared/managers/backend_manager.dart';
- import 'package:soundscape/models/backend/polygons.dart';
- import 'package:soundscape/models/pages/marker_details/marker_details_page.dart';
- import 'package:soundscape/models/effects/vibration_util.dart';
- class MapScreen extends StatefulWidget {
- const MapScreen({
- Key? key
- }) : super(key: key);
- u/override
- State<MapScreen> createState() => _MapScreenState();
- }
- class _MapScreenState extends State<MapScreen> {
- Timer? _locationTimer;
- GoogleMapController? _controller;
- final PolygonsManager _polygonsManager = PolygonsManager();
- final StreamMusicManager _streamMusic = StreamMusicManager();
- final MusicManager _musicManager = MusicManager();
- final BackendManager _backendManager = BackendManager();
- late ParametreProvider parametreProvider;
- String _currentPolygonID = "";
- String _previousPolygonID = "";
- Polygon? currentPolygon;
- SoundscapePolygon? currentSoundscapePolygon;
- MarkerData? currentMarkerData;
- bool isInCurrentPolygon = false;
- bool _isUpdatingLocation = false;
- bool _isMusicLoading = false;
- bool isInChangement = false;
- bool _isTrackChanging = false;
- final Set<Marker> _clickMarkers = {};
- final List<List<double>> _clickPolygons = [];
- LatLng _currentPosition = const LatLng(0, 0);
- u/override
- void initState() {
- super.initState();
- parametreProvider = Provider.of<ParametreProvider>(context, listen: false);
- _startUpdateLocation();
- _setupMusicQueue();
- }
- @override
- void dispose() {
- _locationTimer?.cancel();
- _controller?.dispose();
- super.dispose();
- }
- void _setupMusicQueue() {
- _musicManager.onTrackCompleted = (String polygonId) async {
- if (_isTrackChanging) {
- debugPrint("🎵 Changement de piste déjà en cours, ignore");
- return;
- }
- _isTrackChanging = true;
- debugPrint("🎵 Piste terminée pour polygone: $polygonId");
- try {
- await _streamMusic.onMusicEnded(polygonId);
- } finally {
- await Future.delayed(const Duration(milliseconds: 500));
- _isTrackChanging = false;
- }
- };
- _streamMusic.onTrackEnded = (String? nextTrackPath) async {
- if (isInChangement) {
- debugPrint("🎵 Changement de musique en cours, ignore cette demande");
- return;
- }
- if (nextTrackPath != null && currentSoundscapePolygon != null) {
- isInChangement = true;
- debugPrint("🎵 Lancement de la piste suivante ICI: $nextTrackPath");
- await _musicManager.play(
- nextTrackPath,
- polygonId: currentSoundscapePolygon!.uuid
- );
- debugPrint("JE SUIS ICICICICICIICICICICICICICICICICICIC");
- refreshCurrentPolygon(currentSoundscapePolygon!.uuid);
- debugPrint("🎵 Mise à jour de l'image du marqueur pour le polygone ${currentSoundscapePolygon!.uuid}");
- if (currentMarkerData != null) {
- final markerId = currentMarkerData!.id;
- final musicImagePath = _streamMusic.getCurrentMusicCoverPath;
- debugPrint("🎵 Mise à jour de l'image du marqueur $markerId avec $musicImagePath");
- await _polygonsManager.getMarkersManager.updateMarkerImage(markerId, musicImagePath);
- } else {
- debugPrint("⚠️ currentMarkerData est null, tentative de récupération...");
- final markerData = _polygonsManager.getMarkersManager.getMarkerDataByPolygonId(currentSoundscapePolygon!.uuid);
- if (markerData != null) {
- currentMarkerData = markerData;
- final musicImagePath = _streamMusic.getCurrentMusicCoverPath;
- debugPrint("🎵 Marker récupéré, mise à jour de l'image avec $musicImagePath");
- await _polygonsManager.getMarkersManager.updateMarkerImage(markerData.id, musicImagePath);
- } else {
- debugPrint("❌ Impossible de trouver le marker pour le polygone ${currentSoundscapePolygon!.uuid}");
- }
- }
- isInChangement = false;
- setState(() {});
- }
- };
- }
- void _startUpdateLocation() {
- _locationTimer?.cancel();
- _locationTimer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
- _updateLocation();
- });
- }
- void _updateLocation() async {
- if (_isUpdatingLocation) {
- debugPrint("⏸️ Mise à jour en cours, ignore cet appel");
- return;
- }
- _isUpdatingLocation = true;
- try {
- if (parametreProvider.manualMode) {
- _currentPosition = parametreProvider.manualPosition;
- } else {
- await Provider.of<LocationProvider>(context, listen: false).updateCurrentLocation();
- if (!mounted) return;
- _currentPosition = Provider.of<LocationProvider>(context, listen: false).currentPosition;
- }
- if (parametreProvider.manualPolygon == false) {
- _controller?.animateCamera(CameraUpdate.newLatLng(_currentPosition));
- }
- String newPolygonID = "";
- try {
- newPolygonID = await getCurrentPolygonID(_currentPosition, _polygonsManager);
- } catch (error) {
- debugPrint("❌ Erreur lors de la récupération du polygon ID: $error");
- }
- bool polygonChanged = (newPolygonID != _previousPolygonID);
- _currentPolygonID = newPolygonID;
- if (polygonChanged) {
- debugPrint("🔄 Changement de polygone: $_previousPolygonID -> $_currentPolygonID");
- if (parametreProvider.vibration) {
- if (_currentPolygonID.isNotEmpty) {
- debugPrint("🔔 Vibration pour le polygone $_currentPolygonID");
- VibrationUtil.vibrate();
- } else {
- debugPrint("🔕 Pas de vibration, pas de polygone actif");
- }
- } else {
- debugPrint("🔕 Vibration désactivée dans les paramètres");
- }
- _previousPolygonID = _currentPolygonID;
- refreshCurrentPolygon(_currentPolygonID);
- _musicManager.stop();
- _streamMusic.currentEqualsToNext(null);
- _isMusicLoading = false;
- }
- if (_currentPolygonID != "") {
- await _handleCurrentPolygon();
- _polygonsManager.getMarkersManager.updateMarkerOnTap(_currentPolygonID, () {
- Navigator.push(
- context,
- MaterialPageRoute(
- builder: (context) => MarkerDetailsPage(
- title: currentSoundscapePolygon?.uuid ?? 'Panik',
- description: _streamMusic.getCurrentMusicTitle,
- imagePath: _streamMusic.getCurrentMusicCoverPath,
- nextMusics: _streamMusic.getFullQueue(_currentPolygonID),
- isInPolygon: isInCurrentPolygon,
- ),
- ),
- );
- });
- if (polygonChanged) {
- debugPrint("🔄 Mise à jour des marqueurs pour le polygone $_currentPolygonID");
- }
- } else {
- _handleNoPolygon();
- }
- if (_backendManager.backendIsDead && polygonChanged) {
- _polygonsManager.clearPolygons();
- _polygonsManager.clearMarkers();
- }
- } finally {
- _isUpdatingLocation = false;
- if (mounted) {
- setState(() {});
- }
- }
- }
- Future<void> _handleCurrentPolygon() async {
- setState(() {
- isInCurrentPolygon = true;
- currentPolygon = _polygonsManager.getPolygon(_currentPolygonID);
- currentSoundscapePolygon = _polygonsManager.getSoundscapePolygon(_currentPolygonID);
- currentMarkerData = _polygonsManager.getMarkersManager.getMarkerDataByPolygonId(_currentPolygonID);
- });
- if (currentPolygon == null) {
- _musicManager.stop();
- _streamMusic.currentEqualsToNext(null);
- return;
- }
- if (parametreProvider.volumne == 0) {
- return;
- }
- _musicManager.setVolume(parametreProvider.volumne / 100);
- await _handleMusicForPolygon(currentSoundscapePolygon);
- }
- Future<void> _handleMusicForPolygon(SoundscapePolygon? polygon) async {
- if (polygon == null) return;
- if (_isTrackChanging) {
- debugPrint("[_handleMusicForPolygon] Changement de piste en cours, ignore la gestion de musique");
- return;
- }
- if (_isMusicLoading) {
- debugPrint("[_handleMusicForPolygon] Musique en cours de chargement, ignore cette demande");
- return;
- }
- if (_streamMusic.currentEqualsToNext(polygon)) {
- debugPrint("[_handleMusicForPolygon] Même musique, pas de changement nécessaire");
- if (!_musicManager.isPlaying()) {
- final musicPath = _streamMusic.getCurrentMusicImagePath;
- if (musicPath.isNotEmpty) {
- debugPrint("[_handleMusicForPolygon] Relance la musique existante");
- _musicManager.play(
- musicPath,
- volume: parametreProvider.volumne / 100,
- polygonId: polygon.uuid,
- );
- }
- }
- setState(() {});
- return;
- }
- debugPrint("[_handleMusicForPolygon] Chargement nouvelle musique pour ${polygon.uuid}");
- _isMusicLoading = true;
- try {
- await _streamMusic.chooseMusic(polygon);
- final musicPath = _streamMusic.getCurrentMusicImagePath;
- if (musicPath.isNotEmpty) {
- debugPrint("[_handleMusicForPolygon] Lecture de la nouvelle musique: $musicPath");
- _musicManager.play(
- musicPath,
- volume: parametreProvider.volumne / 100,
- polygonId: polygon.uuid,
- );
- if (currentMarkerData != null) {
- final markerId = currentMarkerData!.id;
- final musicImagePath = _streamMusic.getCurrentMusicCoverPath;
- debugPrint("[_handleMusicForPolygon] Mise à jour de l'image du marqueur $markerId avec $musicImagePath");
- await _polygonsManager.getMarkersManager.updateMarkerImage(markerId, musicImagePath);
- } else {
- debugPrint("[_handleMusicForPolygon] ⚠️ currentMarkerData est null, tentative de récupération...");
- final markerData = _polygonsManager.getMarkersManager.getMarkerDataByPolygonId(polygon.uuid);
- if (markerData != null) {
- currentMarkerData = markerData;
- final musicImagePath = _streamMusic.getCurrentMusicCoverPath;
- debugPrint("[_handleMusicForPolygon] Marker récupéré, mise à jour de l'image avec $musicImagePath");
- await _polygonsManager.getMarkersManager.updateMarkerImage(markerData.id, musicImagePath);
- } else {
- debugPrint("[_handleMusicForPolygon] ❌ Impossible de trouver le marker pour le polygone ${polygon.uuid}");
- }
- }
- } else {
- debugPrint("[_handleMusicForPolygon] ❌ Chemin de musique vide après chargement");
- }
- } catch (e) {
- debugPrint("[_handleMusicForPolygon] ❌ Erreur lors du chargement de la musique: $e");
- } finally {
- _isMusicLoading = false;
- }
- setState(() {});
- }
- void _handleNoPolygon() {
- setState(() {
- isInCurrentPolygon = false;
- currentPolygon = null;
- currentSoundscapePolygon = null;
- currentMarkerData = null;
- });
- _musicManager.stop();
- _streamMusic.currentEqualsToNext(null);
- }
- @override
- Widget build(BuildContext context) {
- bool permissionDenied = Provider.of<LocationProvider>(context).permissionDenied;
- return Scaffold(
- bottomNavigationBar: BottomNavBar(
- currentIndex: 0,
- onTap: (index) {},
- ),
- body: permissionDenied
- ? const Center(child: Text('Location permissions are denied'))
- : Stack(
- fit: StackFit.expand,
- children: [
- GoogleMap(
- style: parametreProvider.style,
- initialCameraPosition: CameraPosition(
- target: _currentPosition,
- zoom: 14,
- ),
- onMapCreated: (controller) {
- _controller = controller;
- },
- onTap: parametreProvider.manualPolygon
- ? (LatLng position) {
- _handleMapTap(position);
- }
- : null,
- // True / False
- myLocationEnabled: !parametreProvider.manualMode,
- myLocationButtonEnabled: false,
- zoomControlsEnabled: false,
- zoomGesturesEnabled: true,
- mapToolbarEnabled: false,
- // Polygons & Markers & Circles
- polygons: _polygonsManager.getPolygons,
- markers: {
- ..._polygonsManager.getMarkers.toSet(),
- if (parametreProvider.manualPolygon) ..._clickMarkers,
- },
- circles: parametreProvider.manualCircle,
- ),
- ButtonsBottomMainPage(
- manualPolygon: parametreProvider.manualPolygon,
- manualMode: parametreProvider.manualMode,
- isInCurrentPolygon: isInCurrentPolygon,
- currentMarkerData: currentMarkerData,
- clickPolygons: _clickPolygons,
- onRefreshPolygonFinished: () {
- parametreProvider.setManualPolygon(false);
- _clickMarkers.clear();
- _clickPolygons.clear();
- }
- ),
- ButtonsTopMainPage(
- manualPolygon: parametreProvider.manualPolygon
- ),
- ],
- ),
- );
- }
- void _handleMapTap(LatLng position) {
- String markerId = 'click_marker_${position.latitude}_${position.longitude}_${DateTime.now().millisecondsSinceEpoch}';
- setState(() {
- _clickMarkers.add(
- Marker(
- markerId: MarkerId(markerId),
- position: position,
- icon: BitmapDescriptor.defaultMarkerWithHue(Random().nextInt(360).toDouble()),
- infoWindow: InfoWindow(
- title: 'Position sélectionnée',
- snippet: '${position.latitude}, ${position.longitude}',
- ),
- ),
- );
- _clickPolygons.add([position.latitude, position.longitude]);
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement