Files
maps-saas/packages/tactical_app/lib/widgets/camera_resection_view.dart
T

498 lines
19 KiB
Dart

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_compass/flutter_compass.dart';
import '../models/angle_unit.dart';
import '../models/landmark.dart';
import '../services/landmark_database.dart';
import '../services/local_sqlite_db.dart';
import '../services/resection_calculator.dart';
import '../services/tactical_api_service.dart';
import 'tactical_crosshair.dart';
class CameraResectionView extends StatefulWidget {
final List<ResectionObservation> observations;
final AngleUnit angleUnit;
final Function(ResectionObservation) onObservationAdded;
final VoidCallback onCalculatePressed;
final VoidCallback onResetPressed;
final VoidCallback onClose;
const CameraResectionView({
super.key,
required this.observations,
required this.angleUnit,
required this.onObservationAdded,
required this.onCalculatePressed,
required this.onResetPressed,
required this.onClose,
});
@override
State<CameraResectionView> createState() => _CameraResectionViewState();
}
class _CameraResectionViewState extends State<CameraResectionView> {
CameraController? _cameraController;
bool _isCameraReady = false;
double _headingDeg = 0.0;
bool _isLockedAnim = false;
// Search state
final TextEditingController _searchController = TextEditingController();
List<TacticalLandmark> _searchResults = [];
bool _isSearching = false;
TacticalLandmark? _selectedLandmark;
@override
void initState() {
super.initState();
_initCamera();
_initCompass();
_initDefaultLandmark();
}
void _initDefaultLandmark() {
final all = LandmarkDatabase.allLandmarks;
if (all.isNotEmpty) {
_selectedLandmark = all[0];
_searchResults = all.take(10).toList();
}
}
Future<void> _initCamera() async {
try {
final cameras = await availableCameras();
if (cameras.isNotEmpty) {
_cameraController = CameraController(
cameras.first,
ResolutionPreset.high,
enableAudio: false,
);
await _cameraController!.initialize();
if (mounted) {
setState(() => _isCameraReady = true);
}
}
} catch (e) {
debugPrint('Camera init exception: $e');
}
}
void _initCompass() {
FlutterCompass.events?.listen((event) {
if (event.heading != null && mounted) {
setState(() {
_headingDeg = (event.heading! + 360) % 360;
});
}
});
}
@override
void dispose() {
_cameraController?.dispose();
_searchController.dispose();
super.dispose();
}
Future<void> _onSearchChanged(String query) async {
final cleanQuery = query.trim();
if (cleanQuery.isEmpty) {
setState(() {
_searchResults = LandmarkDatabase.allLandmarks.take(10).toList();
_isSearching = false;
});
return;
}
setState(() => _isSearching = true);
// 1. Search SQLite Local Places Database (Mosques, Schools, Intersections, Hills)
List<TacticalLandmark> dbResults = [];
try {
dbResults = await LocalSqliteDb.searchPlaces(cleanQuery, limit: 30);
} catch (_) {}
// 2. Search Static Strategic Landmarks
final staticResults = LandmarkDatabase.search(cleanQuery);
// 3. Search Online Geocoding API if local results are few
List<TacticalLandmark> onlineResults = [];
if (dbResults.length < 5) {
try {
onlineResults = await TacticalApiService.searchOnlinePlaces(cleanQuery);
} catch (_) {}
}
final combined = <TacticalLandmark>[...dbResults, ...onlineResults, ...staticResults];
final seen = <String>{};
final unique = <TacticalLandmark>[];
for (final r in combined) {
if (seen.add('${r.name}_${r.lat}_${r.lng}')) {
unique.add(r);
}
}
if (mounted) {
setState(() {
_searchResults = unique;
_isSearching = false;
if (_searchResults.isNotEmpty && !_searchResults.any((l) => l.id == _selectedLandmark?.id)) {
_selectedLandmark = _searchResults[0];
}
});
}
}
void _lockCurrentObservation() {
if (_selectedLandmark == null) return;
final trueAzimuth = ResectionCalculator.getTrueAzimuth(_headingDeg);
final obs = ResectionObservation(
landmark: _selectedLandmark!,
observedAzimuthDeg: _headingDeg,
trueAzimuthDeg: trueAzimuth,
);
setState(() => _isLockedAnim = true);
Future.delayed(const Duration(milliseconds: 300), () {
if (mounted) setState(() => _isLockedAnim = false);
});
widget.onObservationAdded(obs);
// Auto-advance to map calculation if we have 2 observations
final nextObsCount = widget.observations.length +
(widget.observations.any((o) => o.landmark.id == obs.landmark.id) ? 0 : 1);
if (nextObsCount >= 2) {
Future.delayed(const Duration(milliseconds: 400), () {
if (mounted) {
widget.onCalculatePressed();
}
});
return;
}
// Reset search for second landmark
_searchController.clear();
setState(() {
_searchResults = LandmarkDatabase.allLandmarks.where((l) => l.id != _selectedLandmark!.id).take(10).toList();
if (_searchResults.isNotEmpty) {
_selectedLandmark = _searchResults[0];
}
});
}
@override
Widget build(BuildContext context) {
final trueAzimuth = ResectionCalculator.getTrueAzimuth(_headingDeg);
final obsCount = widget.observations.length;
return Scaffold(
backgroundColor: Colors.black,
body: Stack(
children: [
// ── 1. Camera Feed / Viewfinder Background ─────────────────
if (_isCameraReady && _cameraController != null)
SizedBox.expand(
child: FittedBox(
fit: BoxFit.cover,
child: SizedBox(
width: _cameraController!.value.previewSize?.height ?? 1,
height: _cameraController!.value.previewSize?.width ?? 1,
child: CameraPreview(_cameraController!),
),
),
)
else
Container(
decoration: const BoxDecoration(
gradient: RadialGradient(
center: Alignment.center,
radius: 1.2,
colors: [Color(0xFF0F172A), Color(0xFF020617)],
),
),
child: const Center(
child: Icon(Icons.camera_alt, size: 48, color: Color(0xFF38BDF8)),
),
),
// ── 2. Tactical Military Crosshair & Reticle ────────────────
TacticalCrosshair(
headingDeg: _headingDeg,
trueAzimuthDeg: trueAzimuth,
angleUnit: widget.angleUnit,
isAimLocked: _isLockedAnim,
targetName: _selectedLandmark?.name,
),
// ── 3. Top Header: Step Flow + Search Bar ────────────────────
Positioned(
top: 44,
left: 16,
right: 16,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Top Action Row
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
// Step Indicator Badge
Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
decoration: BoxDecoration(
color: const Color(0xF00F172A),
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: obsCount >= 2 ? const Color(0xFF22C55E) : const Color(0xFF0071E3),
width: 1.5,
),
),
child: Row(
children: [
Icon(
obsCount >= 2 ? Icons.check_circle : Icons.gps_fixed,
size: 16,
color: obsCount >= 2 ? const Color(0xFF4ADE80) : const Color(0xFF38BDF8),
),
const SizedBox(width: 8),
Text(
obsCount == 0
? 'الخطوة 1: ابحث وسدد على المعلم الأول'
: (obsCount == 1
? 'الخطوة 2: ابحث وسدد على المعلم الثاني'
: 'تم رصد $obsCount معالم • جاري استخراج الموقع'),
style: TextStyle(
color: obsCount >= 2 ? const Color(0xFF4ADE80) : Colors.white,
fontSize: 11.5,
fontWeight: FontWeight.bold,
),
),
],
),
),
// Close Button
IconButton.filled(
onPressed: widget.onClose,
icon: const Icon(Icons.close, size: 18),
style: IconButton.styleFrom(
backgroundColor: const Color(0xCC0F172A),
foregroundColor: Colors.white,
),
),
],
),
const SizedBox(height: 10),
// Unified Place / Mosque / Landmark Search Field
Container(
decoration: BoxDecoration(
color: const Color(0xF50F172A),
borderRadius: BorderRadius.circular(14),
border: Border.all(color: const Color(0xFF0071E3)),
boxShadow: const [BoxShadow(color: Colors.black54, blurRadius: 15)],
),
child: TextField(
controller: _searchController,
onChanged: _onSearchChanged,
style: const TextStyle(color: Colors.white, fontSize: 13),
decoration: InputDecoration(
hintText: 'ابحث عن أي مسجد، مبنى، قلعة، تقاطع، أو معلم...',
hintStyle: const TextStyle(color: Color(0xFF94A3B8), fontSize: 12),
prefixIcon: const Icon(Icons.search, color: Color(0xFF38BDF8), size: 20),
suffixIcon: _searchController.text.isNotEmpty
? IconButton(
icon: const Icon(Icons.clear, size: 16, color: Colors.white70),
onPressed: () {
_searchController.clear();
_onSearchChanged('');
},
)
: null,
contentPadding: const EdgeInsets.symmetric(vertical: 12),
border: InputBorder.none,
),
),
),
if (_isSearching) ...[
const SizedBox(height: 4),
const LinearProgressIndicator(minHeight: 2, color: Color(0xFF0071E3), backgroundColor: Colors.transparent),
],
// Search Results Dropdown List (if search has text or active)
if (_searchController.text.isNotEmpty && _searchResults.isNotEmpty)
Container(
margin: const EdgeInsets.only(top: 6),
constraints: const BoxConstraints(maxHeight: 180),
decoration: BoxDecoration(
color: const Color(0xF80F172A),
borderRadius: BorderRadius.circular(14),
border: Border.all(color: Colors.white12),
boxShadow: const [BoxShadow(color: Colors.black87, blurRadius: 20)],
),
child: ListView.separated(
padding: const EdgeInsets.symmetric(vertical: 4),
shrinkWrap: true,
itemCount: _searchResults.length,
separatorBuilder: (_, __) => const Divider(color: Colors.white10, height: 1),
itemBuilder: (context, idx) {
final lm = _searchResults[idx];
final isSelected = lm.id == _selectedLandmark?.id;
return ListTile(
dense: true,
visualDensity: VisualDensity.compact,
leading: Icon(
lm.typeIcon,
color: isSelected ? const Color(0xFF38BDF8) : const Color(0xFF94A3B8),
size: 18,
),
title: Text(
lm.name,
style: TextStyle(
color: isSelected ? const Color(0xFF38BDF8) : Colors.white,
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
'${lm.region} • ${lm.elevationM}م',
style: const TextStyle(color: Color(0xFF64748B), fontSize: 10),
),
trailing: isSelected ? const Icon(Icons.check, color: Color(0xFF38BDF8), size: 16) : null,
onTap: () {
setState(() => _selectedLandmark = lm);
_searchController.text = lm.name;
},
);
},
),
),
],
),
),
// ── 4. Bottom HUD: Active Target Details & Lock Action ───────
Positioned(
bottom: 24,
left: 16,
right: 16,
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: const Color(0xF50F172A),
borderRadius: BorderRadius.circular(20),
border: Border.all(color: const Color(0xFF0071E3), width: 1.5),
boxShadow: const [BoxShadow(color: Colors.black87, blurRadius: 25)],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Targeted Landmark Card
if (_selectedLandmark != null)
Container(
margin: const EdgeInsets.only(bottom: 12),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: const Color(0x661E293B),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.white12),
),
child: Row(
children: [
Icon(_selectedLandmark!.typeIcon, color: const Color(0xFF38BDF8), size: 22),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_selectedLandmark!.name,
style: const TextStyle(
color: Colors.white,
fontSize: 13,
fontWeight: FontWeight.bold,
),
overflow: TextOverflow.ellipsis,
),
Text(
'${_selectedLandmark!.region} • إحداثيات: ${_selectedLandmark!.lat.toStringAsFixed(4)}, ${_selectedLandmark!.lng.toStringAsFixed(4)}',
style: const TextStyle(color: Color(0xFF94A3B8), fontSize: 10),
),
],
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: const Color(0x330071E3),
borderRadius: BorderRadius.circular(8),
),
child: Text(
AngleFormatter.format(trueAzimuth, widget.angleUnit, includeLabel: false),
style: const TextStyle(
color: Color(0xFF38BDF8),
fontSize: 12,
fontWeight: FontWeight.w900,
),
),
),
],
),
),
// Main Lock / Action Button
Row(
children: [
Expanded(
child: ElevatedButton.icon(
onPressed: _selectedLandmark != null ? _lockCurrentObservation : null,
icon: Icon(
obsCount >= 1 ? Icons.my_location : Icons.lock_outline,
size: 18,
),
label: Text(
obsCount == 0
? 'تثبيت رصد المعلم الأول'
: 'تثبيت رصد المعلم الثاني (استخراج الموقع فوراً)',
style: const TextStyle(fontSize: 12.5, fontWeight: FontWeight.w900),
),
style: ElevatedButton.styleFrom(
backgroundColor: obsCount >= 1 ? const Color(0xFF22C55E) : const Color(0xFF0071E3),
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
elevation: 4,
),
),
),
if (obsCount > 0) ...[
const SizedBox(width: 8),
IconButton.filledTonal(
onPressed: widget.onResetPressed,
icon: const Icon(Icons.refresh, size: 18),
style: IconButton.styleFrom(
backgroundColor: const Color(0x33EF4444),
foregroundColor: const Color(0xFFF87171),
),
),
],
],
),
],
),
),
),
],
),
);
}
}