dart

Anonymous
Dart
09/18/2025 10:56 AM
40.0 KB
19
Indexable
Never
// CameraFeetDetection - Mobile front camera version of TakePictureScreen
import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'dart:isolate';
import 'dart:math' as math;
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image/image.dart' as img;
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:tflite_flutter/tflite_flutter.dart';

import 'package:stride/config/theme/app_theme.dart';
import 'package:stride/config/theme/color_manager.dart';
import 'package:stride/core/common/constant/strings.dart';
import 'package:stride/core/common/helper/main_helper.dart';
import 'package:stride/core/common/shared_widgets/custom_bottom_sheet.dart';
import 'package:stride/core/common/shared_widgets/loading_widget.dart';
import 'package:stride/feature/camera_detection/presentation/notifier/bluetooth_notifier.dart';
import 'package:stride/feature/home_feature/presentation/home_page/notifier/home_notifier.dart';
import 'package:stride/feature/home_feature/presentation/home_page/page/home_page.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:stride/feature/intake_feature/data/models/intake_param.dart';
import 'package:stride/feature/intake_feature/presentation/page/intake_questions_page.dart';
import '../../../../config/navigator/navigator.dart';
import '../../../../core/common/constant/assets.dart';

// -------------------- Math helpers (top-level) --------------------
double _sigmoid(double x) => 1.0 / (1.0 + math.exp(-x));

/// (kept for compatibility with your old code, not used now)
Future<List?> _preprocessTo4DInput(Map<String, dynamic> params) async {
  try {
    final bytes = params['imageBytes'] as Uint8List;
    final targetW = params['targetW'] as int;
    final targetH = params['targetH'] as int;
    final raw = img.decodeImage(bytes);
    if (raw == null) return null;
    final resized = img.copyResize(raw, width: targetW, height: targetH);
    final input = List.generate(
      1,
      (_) => List.generate(
        targetH,
        (_) => List.generate(targetW, (_) => List.filled(3, 0.0)),
      ),
    );
    for (int y = 0; y < targetH; y++) {
      for (int x = 0; x < targetW; x++) {
        final p = resized.getPixel(x, y);
        input[0][y][x][0] = p.r / 255.0;
        input[0][y][x][1] = p.g / 255.0;
        input[0][y][x][2] = p.b / 255.0;
      }
    }
    return input;
  } catch (e) {
    debugPrint('preprocess error: $e');
    return null;
  }
}

// -------------------- Long-lived preprocessor isolate --------------------
class _PreprocessRequest {
  final int id;
  final Uint8List y;
  final Uint8List u;
  final Uint8List v;
  final int w, h;
  final int yRowStride, uvRowStride, uvPixelStride;
  final int targetW, targetH;
  final int sensorOrientation;
  _PreprocessRequest({
    required this.id,
    required this.y,
    required this.u,
    required this.v,
    required this.w,
    required this.h,
    required this.yRowStride,
    required this.uvRowStride,
    required this.uvPixelStride,
    required this.targetW,
    required this.targetH,
    required this.sensorOrientation,
  });
}

class _PreprocessResponse {
  final int id;
  final Float32List? data; // NHWC float [1,H,W,3] flattened => H*W*3
  _PreprocessResponse(this.id, this.data);
}

void _preprocessIsolate(SendPort mainSendPort) {
  final port = ReceivePort();
  mainSendPort.send(port.sendPort);

  Float32List? buffer;
  int bufW = 0, bufH = 0;

  int clamp(int v, int lo, int hi) => v < lo ? lo : (v > hi ? hi : v);

  port.listen((message) {
    if (message is _PreprocessRequest) {
      try {
        final y = message.y;
        final u = message.u;
        final v = message.v;
        final w = message.w;
        final h = message.h;
        final yRowStride = message.yRowStride;
        final uvRowStride = message.uvRowStride;
        final uvPixelStride = message.uvPixelStride;
        final targetW = message.targetW;
        final targetH = message.targetH;
        final sensorOrientation = message.sensorOrientation;

        if (buffer == null || bufW != targetW || bufH != targetH) {
          buffer = Float32List(targetH * targetW * 3);
          bufW = targetW;
          bufH = targetH;
        }
        final out = buffer!;

        int srcW = w, srcH = h;
        if (sensorOrientation == 90 || sensorOrientation == 270) {
          srcW = h;
          srcH = w;
        }

        final double scaleX = srcW / targetW;
        final double scaleY = srcH / targetH;

        int baseIndex(int y, int x) => ((y * targetW + x) * 3);

        for (int ty = 0; ty < targetH; ty++) {
          for (int tx = 0; tx < targetW; tx++) {
            final rx = (tx * scaleX).floor();
            final ry = (ty * scaleY).floor();

            int sx0, sy0;
            switch (sensorOrientation) {
              case 90:
                sx0 = ry;
                sy0 = (w - 1) - rx;
                break;
              case 180:
                sx0 = (w - 1) - rx;
                sy0 = (h - 1) - ry;
                break;
              case 270:
                sx0 = (h - 1) - ry;
                sy0 = rx;
                break;
              default:
                sx0 = rx;
                sy0 = ry;
            }

            sx0 = clamp(sx0, 0, w - 1);
            sy0 = clamp(sy0, 0, h - 1);

            final int yIndex = sy0 * yRowStride + sx0;
            final int yp = y[yIndex];

            final int uvX = (sx0 >> 1);
            final int uvY = (sy0 >> 1);
            final int uvIndex = uvY * uvRowStride + uvX * uvPixelStride;

            final int up = u[uvIndex];
            final int vp = v[uvIndex];

            // YUV420 -> RGB (BT.601 approx)
            double r = yp + vp * 1.403 - 179.456;
            double g = yp - up * 0.344 - vp * 0.714 + 135.459;
            double b = yp + up * 1.770 - 226.816;

            if (r < 0) r = 0; else if (r > 255) r = 255;
            if (g < 0) g = 0; else if (g > 255) g = 255;
            if (b < 0) b = 0; else if (b > 255) b = 255;

            final int base = baseIndex(ty, tx);
            out[base] = r / 255.0;
            out[base + 1] = g / 255.0;
            out[base + 2] = b / 255.0;
          }
        }

        mainSendPort.send(_PreprocessResponse(message.id, out));
      } catch (_) {
        mainSendPort.send(_PreprocessResponse(message.id, null));
      }
    }
  });
}

// -------------------- Optional ui.Image conversion (kept, unused hot-path) --------------------
Future<ui.Image?> _cameraImageToUiImage(CameraImage cameraImage) async {
  try {
    final img.Image? imgLib = await _convertCameraImage(cameraImage);
    if (imgLib == null) return null;
    final pngBytes = img.encodePng(imgLib);
    final ui.Codec codec =
        await ui.instantiateImageCodec(Uint8List.fromList(pngBytes));
    final ui.FrameInfo frameInfo = await codec.getNextFrame();
    return frameInfo.image;
  } catch (e) {
    debugPrint('Error converting camera image: $e');
    return null;
  }
}

Future<img.Image?> _convertCameraImage(CameraImage cameraImage) async {
  try {
    if (cameraImage.format.group == ImageFormatGroup.yuv420) {
      return _convertYUV420ToImage(cameraImage);
    } else if (cameraImage.format.group == ImageFormatGroup.bgra8888) {
      return _convertBGRA8888ToImage(cameraImage);
    }
    return null;
  } catch (e) {
    debugPrint('Error in convertCameraImage: $e');
    return null;
  }
}

img.Image _convertYUV420ToImage(CameraImage cameraImage) {
  final int width = cameraImage.width;
  final int height = cameraImage.height;
  final int uvRowStride = cameraImage.planes[1].bytesPerRow;
  final int uvPixelStride = cameraImage.planes[1].bytesPerPixel!;
  final img.Image image = img.Image(width: width, height: height);
  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      final int uvIndex =
          uvPixelStride * (x >> 1) + uvRowStride * (y >> 1);
      final int index = y * width + x;
      final yp = cameraImage.planes[0].bytes[index];
      final up = cameraImage.planes[1].bytes[uvIndex];
      final vp = cameraImage.planes[2].bytes[uvIndex];
      int r = (yp + vp * 1436 / 1024 - 179).round().clamp(0, 255);
      int g = (yp - up * 46549 / 131072 + 44 - vp * 93604 / 131072 + 91)
          .round()
          .clamp(0, 255);
      int b = (yp + up * 1814 / 1024 - 227).round().clamp(0, 255);
      image.setPixelRgb(x, y, r, g, b);
    }
  }
  return image;
}

img.Image _convertBGRA8888ToImage(CameraImage cameraImage) {
  final img.Image image =
      img.Image(width: cameraImage.width, height: cameraImage.height);
  final Uint8List bytes = cameraImage.planes[0].bytes;
  for (int i = 0; i < bytes.length; i += 4) {
    final int b = bytes[i];
    final int g = bytes[i + 1];
    final int r = bytes[i + 2];
    final int a = bytes[i + 3];
    final int pixelIndex = i ~/ 4;
    final int x = pixelIndex % cameraImage.width;
    final int y = pixelIndex ~/ cameraImage.width;
    if (x < cameraImage.width && y < cameraImage.height) {
      image.setPixelRgba(x, y, r, g, b, a);
    }
  }
  return image;
}

// ----------------------------- Screen -----------------------------
class CameraFeetDetection extends StatefulWidget {
  const CameraFeetDetection({super.key});

  @override
  State<CameraFeetDetection> createState() => _CameraFeetDetectionState();
}

class _CameraFeetDetectionState extends State<CameraFeetDetection>
    with TickerProviderStateMixin {
  late HomeNotifier _homeNotifier;

  // Camera
  CameraController? _cameraController;
  bool _isCameraInitialized = false;
  String? _cameraError;

  // orientation/mirroring & raw frame cache
  CameraImage? _latestCamImage;
  int _sensorOrientation = 0;
  bool _isFrontCamera = false;

  // detection state
  bool _footDetected = false;
  bool _isTakingPicture = false;
  bool _detectionTimeoutReached = false;
  late DateTime _detStart;
  static const int _timeoutSec = 15;

  // animation
  late AnimationController _streamingAnimation;
  late AnimationController _streamingController;
  Timer? _poseCheckTimer;

  // Both feet scanning logic
  bool leftCaptured = false;
  bool rightCaptured = false;
  String currentScanningFoot = 'left';
  bool isBothFeetScan = false;

  // TFLite
  Interpreter? _interpreter;
  bool _tfliteInitialized = false;
  int _inW = 640, _inH = 640;
  bool _channelFirst = true;
  int _numChannels = 9;
  int _numAnchors = 8400;

  // Fast I/O buffers
  Float32List? _inputF32;   // length _inH * _inW * 3
  Float32List? _outputF32;  // length _numChannels * _numAnchors (batch=1)

  // performance
  bool _closing = false;
  bool _isProcessing = false;
  int _frameSkipCounter = 0;

  // Preprocessor isolate
  Isolate? _prepIsolate;
  SendPort? _prepSend;
  final _prepRespPort = ReceivePort();
  int _prepSeq = 0;
  final Map<int, Completer<Float32List?>> _prepWaiters = {};

  @override
  void initState() {
    super.initState();

    _homeNotifier = Provider.of<HomeNotifier>(context, listen: false);

    final scanFoot = _homeNotifier.statusEntity.scanData?.foot ?? 'left';
    isBothFeetScan = scanFoot == 'both';
    currentScanningFoot = isBothFeetScan ? 'left' : scanFoot;

    _streamingAnimation = AnimationController(
      duration: const Duration(seconds: 6),
      vsync: this,
    )..repeat();
    _streamingController = AnimationController(
      duration: const Duration(seconds: 3),
      vsync: this,
    )..repeat();

    _detStart = DateTime.now();

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await _startPreprocessor();
      await _initializeCamera();
    });
  }

  // ------------------- Preprocessor isolate control -------------------
  Future<void> _startPreprocessor() async {
    _prepIsolate = await Isolate.spawn(_preprocessIsolate, _prepRespPort.sendPort);
    final first = await _prepRespPort.first;
    if (first is SendPort) {
      _prepSend = first;
    }
    _prepRespPort.listen((msg) {
      if (msg is SendPort) return;
      if (msg is _PreprocessResponse) {
        final c = _prepWaiters.remove(msg.id);
        c?.complete(msg.data);
      }
    });
  }

  Future<void> _stopPreprocessor() async {
    _prepIsolate?.kill(priority: Isolate.immediate);
    _prepIsolate = null;
    _prepSend = null;
    _prepWaiters.clear();
  }

  Future<Float32List?> _preprocessYuvOnIsolate(CameraImage frame) async {
    if (_prepSend == null) return null;
    final id = ++_prepSeq;
    final c = Completer<Float32List?>();
    _prepWaiters[id] = c;

    _prepSend!.send(_PreprocessRequest(
      id: id,
      y: frame.planes[0].bytes,
      u: frame.planes[1].bytes,
      v: frame.planes[2].bytes,
      w: frame.width,
      h: frame.height,
      yRowStride: frame.planes[0].bytesPerRow,
      uvRowStride: frame.planes[1].bytesPerRow,
      uvPixelStride: frame.planes[1].bytesPerPixel ?? 1,
      targetW: _inW,
      targetH: _inH,
      sensorOrientation: _sensorOrientation,
    ));

    return c.future.timeout(const Duration(seconds: 2), onTimeout: () {
      _prepWaiters.remove(id);
      return null;
    });
  }

  // ------------------- Camera & TFLite setup -------------------
  Future<void> _initializeCamera() async {
    try {
      final cameras = await availableCameras();
      if (cameras.isEmpty) {
        setState(() => _cameraError = 'No cameras available');
        return;
      }

      // Find front camera
      CameraDescription? frontCamera;
      for (final camera in cameras) {
        if (camera.lensDirection == CameraLensDirection.front) {
          frontCamera = camera;
          break;
        }
      }
      frontCamera ??= cameras.first;

      _isFrontCamera = frontCamera.lensDirection == CameraLensDirection.front;
      _sensorOrientation = frontCamera.sensorOrientation;

      // Lower res to reduce YUV bandwidth & GC
      _cameraController = CameraController(
        frontCamera,
        ResolutionPreset.low,
        enableAudio: false,
        imageFormatGroup: ImageFormatGroup.yuv420,
      );

      await _cameraController!.initialize();
      await _cameraController!.lockCaptureOrientation(DeviceOrientation.portraitUp);

      // Start image stream (cache frames only)
      _cameraController!.startImageStream(_processCameraImage);

      await _initTFLiteModel();
      _startOptimizedDetectionLoop();

      setState(() => _isCameraInitialized = true);
    } catch (e) {
      debugPrint('Camera initialization error: $e');
      setState(() => _cameraError = e.toString());
    }
  }

  void _processCameraImage(CameraImage image) {
    if (_closing) return;
    _latestCamImage = image; // lightweight cache
  }

  Future<void> _initTFLiteModel() async {
    try {
      final options = InterpreterOptions()
        ..threads = math.max(2, (Platform.numberOfProcessors / 2).floor());

      // Safer cross-version: avoid hard GPU class refs; try NNAPI only
      try {
        // ignore: deprecated_member_use, invalid_use_of_visible_for_testing_member
        options.useNnApiForAndroid = Platform.isAndroid;
      } catch (_) {}

      final interpreter = await Interpreter.fromAsset(
        'assets/models/feet_float16.tflite',
        options: options,
      );
      _interpreter = interpreter;
      _tfliteInitialized = true;

      // Input shape
      final inTensors = interpreter.getInputTensors();
      if (inTensors.isNotEmpty) {
        final shape = inTensors.first.shape; // [1, H, W, 3]
        if (shape.length == 4) {
          _inH = shape[1];
          _inW = shape[2];
        }
        debugPrint('Model input shape: $shape => $_inW x $_inH');
      }

      // Output shape
      final outTensors = interpreter.getOutputTensors();
      if (outTensors.isNotEmpty) {
        final s = outTensors.first.shape; // [1, C, N] or [1, N, C]
        if (s.length == 3) {
          if (s[1] <= 32 && s[2] >= 1000) {
            _channelFirst = true;       // [1, C, N]
            _numChannels = s[1];
            _numAnchors = s[2];
          } else {
            _channelFirst = false;      // [1, N, C]
            _numAnchors = s[1];
            _numChannels = s[2];
          }
        }
        debugPrint(
            'Model output shape=$s channelFirst=$_channelFirst C=$_numChannels N=$_numAnchors');
      }

      // Allocate flat buffers
      _inputF32 = Float32List(_inH * _inW * 3);
      _outputF32 = Float32List(_numChannels * _numAnchors); // batch=1 ignored

      debugPrint('TFLite ready with fast buffers.');
    } catch (e) {
      debugPrint('TFLite initialization error: $e');
      rethrow;
    }
  }

  // ------------------- Detection loop (fast path) -------------------
  void _startOptimizedDetectionLoop() {
    _poseCheckTimer?.cancel();
    _poseCheckTimer = Timer.periodic(const Duration(milliseconds: 250), (_) async {
      try {
        if (_closing) return;

        // Timeout check
        final elapsed = DateTime.now().difference(_detStart).inSeconds;
        if (!_footDetected && !_detectionTimeoutReached && elapsed >= _timeoutSec) {
          debugPrint('Detection timeout reached ($_timeoutSec s).');
          _detectionTimeoutReached = true;

          _poseCheckTimer?.cancel();
          _poseCheckTimer = null;
          if (_streamingController.isAnimating) {
            try {
              _streamingController.stop();
            } catch (_) {}
          }

          if (mounted) setState(() {});
          return;
        }

        if (_detectionTimeoutReached || _isTakingPicture || _isProcessing) return;
        if (!_tfliteInitialized) return;

        // Throttle (skip more frames if device is weaker)
        _frameSkipCounter++;
        if (_frameSkipCounter % 3 != 0) return;

        final frame = _latestCamImage;
        if (frame == null) return;

        _isProcessing = true;

        // 1) Preprocess on long-lived isolate -> Float32List NHWC (H*W*3)
        final Float32List? inputFloat = await _preprocessYuvOnIsolate(frame);
        if (inputFloat == null) return;
        if (_inputF32 == null || _outputF32 == null) return;

        // Copy Float32List for safety (same len)
        _inputF32!.setAll(0, inputFloat);

        // 2) Try fast tensor buffer API if present; otherwise fallback to run()
        bool usedBufferApi = false;
        try {
          final dynamic inputTensor = _interpreter!.getInputTensors().first;
          inputTensor.copyFromBuffer(_inputF32!); // dynamic to avoid static error
          await _interpreter!.invoke();
          final dynamic outTensor = _interpreter!.getOutputTensors().first;
          outTensor.copyTo(_outputF32!);
          usedBufferApi = true;
        } catch (e) {
          // Fallback: nested list run
          final input4d = _floatNHWCToNested(_inputF32!, _inH, _inW);
          final outputNested = _allocOutputNested(_channelFirst, _numChannels, _numAnchors);
          _interpreter!.run(input4d, outputNested);
          _flattenOutputNested(outputNested, _outputF32!, _channelFirst, _numChannels, _numAnchors);
        }

        // 3) Parse confidence from flat buffer
        final conf = _computeMaxConfidenceFlat(
          _outputF32!,
          _channelFirst,
          _numChannels,
          _numAnchors,
        );

        assert(() {
          log('Foot confidence: ${(conf * 100).toStringAsFixed(2)}% (fastApi=$usedBufferApi)');
          return true;
        }());

        final detected = conf > 0.85;

        if (!_footDetected && detected) {
          _footDetected = true;
          _poseCheckTimer?.cancel();
          _poseCheckTimer = null;
          if (_streamingController.isAnimating) {
            try {
              _streamingController.stop();
            } catch (_) {}
          }
          if (mounted) setState(() {});
          await _capturePhoto();
        } else {
          if (mounted) setState(() => _footDetected = detected);
        }
      } catch (e) {
        debugPrint('Error in detection loop: $e');
      } finally {
        _isProcessing = false;

        if (_closing && _tfliteInitialized) {
          try {
            _interpreter?.close();
          } catch (_) {}
          _tfliteInitialized = false;
        }
      }
    });
  }

  // ---- helpers for fallback run() ----
  List _floatNHWCToNested(Float32List nhwc, int h, int w) {
    int idx = 0;
    final out = List.generate(
      1,
      (_) => List.generate(
        h,
        (_) => List.generate(
          w,
          (_) {
            final r = nhwc[idx++]; // R
            final g = nhwc[idx++]; // G
            final b = nhwc[idx++]; // B
            return [r, g, b];
          },
        ),
      ),
    );
    return out;
  }

  List _allocOutputNested(bool channelFirst, int C, int N) {
    if (channelFirst) {
      return List.generate(
        1,
        (_) => List.generate(
          C,
          (_) => List.filled(N, 0.0),
        ),
      );
    } else {
      return List.generate(
        1,
        (_) => List.generate(
          N,
          (_) => List.filled(C, 0.0),
        ),
      );
    }
  }

  void _flattenOutputNested(
    List nested,
    Float32List flat,
    bool channelFirst,
    int C,
    int N,
  ) {
    if (channelFirst) {
      // [1, C, N]
      int k = 0;
      for (int c = 0; c < C; c++) {
        final row = nested[0][c] as List;
        for (int i = 0; i < N; i++) {
          flat[k++] = (row[i] as num).toDouble();
        }
      }
    } else {
      // [1, N, C]
      int k = 0;
      for (int i = 0; i < N; i++) {
        final row = nested[0][i] as List;
        for (int c = 0; c < C; c++) {
          flat[k++] = (row[c] as num).toDouble();
        }
      }
    }
  }

  double _computeMaxConfidenceFlat(
    Float32List flat,
    bool channelFirst,
    int C,
    int N,
  ) {
    double maxConf = 0.0;
    if (channelFirst) {
      // [C, N]
      for (int i = 0; i < N; i++) {
        final double obj = _sigmoid(flat[4 * N + i]);
        double maxCls = 0.0;
        if (C > 5) {
          for (int c = 5; c < C; c++) {
            final double v = _sigmoid(flat[c * N + i]);
            if (v > maxCls) maxCls = v;
          }
        } else {
          maxCls = 1.0;
        }
        final conf = obj * maxCls;
        if (conf > maxConf) maxConf = conf;
      }
    } else {
      // [N, C]
      for (int i = 0; i < N; i++) {
        final base = i * C;
        final double obj = _sigmoid(flat[base + 4]);
        double maxCls = 0.0;
        if (C > 5) {
          for (int c = 5; c < C; c++) {
            final double v = _sigmoid(flat[base + c]);
            if (v > maxCls) maxCls = v;
          }
        } else {
          maxCls = 1.0;
        }
        final conf = obj * maxCls;
        if (conf > maxConf) maxConf = conf;
      }
    }
    return maxConf;
  }

  @override
  void dispose() {
    _poseCheckTimer?.cancel();
    _poseCheckTimer = null;

    _closing = true;

    if (_streamingController.isAnimating) {
      try {
        _streamingController.stop();
      } catch (_) {}
    }
    if (_streamingAnimation.isAnimating) {
      try {
        _streamingAnimation.stop();
      } catch (_) {}
    }
    _streamingController.dispose();
    _streamingAnimation.dispose();

    _cameraController?.stopImageStream();
    _cameraController?.dispose();

    if (_tfliteInitialized) {
      if (_isProcessing) {
        _closing = true;
      } else {
        try {
          _interpreter?.close();
        } catch (_) {}
        _tfliteInitialized = false;
      }
    }

    _stopPreprocessor();
    super.dispose();
  }

  // ------------------- Capture with normalized orientation -------------------
  Future<void> _capturePhoto() async {
    if (_isTakingPicture || _cameraController == null) return;

    setState(() => _isTakingPicture = true);

    try {
      final XFile imageFile = await _cameraController!.takePicture();
      final bytes = await imageFile.readAsBytes();

      String finalPath;

      // Normalize orientation and mirroring for front camera
      try {
        final img.Image? decoded = img.decodeImage(bytes);
        if (decoded != null) {
          img.Image fixed = decoded;

          switch (_sensorOrientation) {
            case 90:
              fixed = img.copyRotate(fixed, angle: 90);
              break;
            case 180:
              fixed = img.copyRotate(fixed, angle: 180);
              break;
            case 270:
              fixed = img.copyRotate(fixed, angle: 270);
              break;
            default:
              break;
          }

          // Mirror to match selfie preview. Remove if backend expects non-mirrored.
          if (_isFrontCamera) {
            fixed = img.flipHorizontal(fixed);
          }

          final normalizedBytes = img.encodeJpg(fixed, quality: 95);
          final dir = await getTemporaryDirectory();
          finalPath =
              '${dir.path}/captured_${DateTime.now().millisecondsSinceEpoch}.jpg';
          final file = File(finalPath);
          await file.writeAsBytes(normalizedBytes);
        } else {
          final dir = await getTemporaryDirectory();
          finalPath =
              '${dir.path}/captured_${DateTime.now().millisecondsSinceEpoch}.jpg';
          final file = File(finalPath);
          await file.writeAsBytes(bytes);
        }
      } catch (e) {
        debugPrint('Normalize capture error: $e');
        final dir = await getTemporaryDirectory();
        finalPath =
            '${dir.path}/captured_${DateTime.now().millisecondsSinceEpoch}.jpg';
        final file = File(finalPath);
        await file.writeAsBytes(bytes);
      }

      if (_footDetected || _detectionTimeoutReached) {
        if (!mounted) return;

        if (isBothFeetScan) {
          if (currentScanningFoot == 'left' && !leftCaptured) {
            log('Capturing left foot');
            await _savePicture(finalPath, 'left', false);

            leftCaptured = true;
            navigatePushAndRemoveUntil(
              context: context,
              pageName: const IntakeQuestionsPage(title: 'right'),
            );
            return;
          } else if (currentScanningFoot == 'right' && !rightCaptured) {
            log('Capturing right foot');
            await _savePicture(finalPath, 'right', true);

            rightCaptured = true;
            navigatePushAndRemoveUntil(
              context: context,
              pageName: const HomePage(),
            );
            return;
          }
        } else {
          log('Capturing single foot: $currentScanningFoot');
          await _savePicture(finalPath, currentScanningFoot, true);
          navigatePushAndRemoveUntil(
              context: context, pageName: const HomePage());
        }
      } else {
        Helper().handlelocalErrors(title: 'The foot is outside the shape');
      }
    } catch (e) {
      debugPrint("Capture error: $e");
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Capture error: ${e.toString()}')),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isTakingPicture = false);
      }
    }
  }

  Future<void> _savePicture(String path, String foot, bool isLastFoot) async {
    try {
      final file = File(path);
      if (!await file.exists()) {
        throw Exception('Image file not found at path: $path');
      }

      if (mounted) {
        _showBottomSheet(context);

        await Future.delayed(const Duration(seconds: 2), () {
          if (mounted) {
            Provider.of<HomeNotifier>(context, listen: false).goToReview();
            if (isLastFoot) {
              navigatePushAndRemoveUntil(
                  context: context, pageName: const HomePage());
            }
          }
        });
      }
    } catch (e) {
      debugPrint("Error in _savePicture: $e");
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to save image: ${e.toString()}')),
        );
      }
    }
  }

  String _getCurrentFootDisplayText() {
    if (isBothFeetScan) {
      if (currentScanningFoot == 'left' && !leftCaptured) {
        return 'Position Your Left Foot';
      } else if (currentScanningFoot == 'right' && !rightCaptured) {
        return 'Position Your Right Foot';
      }
    }
    return 'Position Your Foot';
  }

  // ------------------- UI -------------------
  @override
  Widget build(BuildContext context) {
    final showLoaderOverlay = !_isCameraInitialized || _cameraError != null;

    return Scaffold(
      backgroundColor: ColorManager.white,
      appBar: AppBar(
        title: Text(
          _getCurrentFootDisplayText(),
          style: Theme.of(context).textTheme.headlineMedium,
        ),
        automaticallyImplyLeading: false,
        leading: IconButton(
          onPressed: () {
            navigatePushAndRemoveUntil(
                context: context, pageName: const HomePage());
          },
          icon: const Icon(Icons.close),
        ),
      ),
      body: _footDetected
          ? _footAnimation()
          : Stack(
              fit: StackFit.expand,
              alignment: Alignment.center,
              children: [
                // Camera preview (fast, correct rotation)
                if (_isCameraInitialized && _cameraController != null)
                  Transform(
                    alignment: Alignment.center,
                    transform: _isFrontCamera
                        ? (Matrix4.identity()..rotateY(math.pi)) // mirror selfie
                        : Matrix4.identity(),
                    child: CameraPreview(_cameraController!),
                  ),

                // Silhouette overlay
                Align(
                  alignment: Alignment.bottomCenter,
                  child: Padding(
                    padding: _detectionTimeoutReached
                        ? const EdgeInsets.only(bottom: 120, top: 10)
                        : const EdgeInsets.only(bottom: 40, top: 30),
                    child: ColorFiltered(
                      colorFilter: ColorFilter.mode(
                        _detectionTimeoutReached
                            ? Colors.white
                            : _footDetected
                                ? Colors.green
                                : Colors.red,
                        BlendMode.srcIn,
                      ),
                      child: Image.asset(
                        currentScanningFoot == 'left'
                            ? Assets.leftFoot
                            : Assets.rightFoot,
                        width: MediaQuery.sizeOf(context).width * 0.9,
                        height: MediaQuery.sizeOf(context).height,
                        fit: BoxFit.fill,
                      ),
                    ),
                  ),
                ),

                // Timeout sheet
                if (_detectionTimeoutReached)
                  Positioned(
                    bottom: 0,
                    child: _TimeoutSheet(
                      foot: currentScanningFoot,
                      onCapture: _isTakingPicture ? null : _capturePhoto,
                      isTakingPicture: _isTakingPicture,
                    ),
                  ),

                // Loading/error overlay
                if (showLoaderOverlay)
                  Container(
                    color: Colors.black54,
                    child: Center(
                      child: _cameraError == null
                          ? const CircularProgressIndicator()
                          : Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                const Icon(Icons.error, color: Colors.white),
                                const SizedBox(height: 8),
                                Padding(
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 16),
                                  child: Text(
                                    _cameraError ??
                                        'Camera initialization failed',
                                    style: const TextStyle(color: Colors.white),
                                    textAlign: TextAlign.center,
                                  ),
                                ),
                                const SizedBox(height: 12),
                                ElevatedButton(
                                  onPressed: _initializeCamera,
                                  child: const Text('Retry'),
                                ),
                              ],
                            ),
                    ),
                  ),
              ],
            ),
    );
  }

  Stack _footAnimation() {
    return Stack(
      children: [
        AnimatedBuilder(
          animation: _streamingAnimation,
          builder: (context, child) {
            final screenHeight = MediaQuery.sizeOf(context).height;
            final scanY = _streamingAnimation.value * screenHeight;

            return Center(
              child: ClipRect(
                clipper: ScanClipper(scanY),
                child: SvgPicture.asset(
                  currentScanningFoot == 'left'
                      ? Assets.feetlogo2
                      : Assets.feetlogo,
                ),
              ),
            );
          },
        ),
        AnimatedBuilder(
          animation: _streamingAnimation,
          builder: (context, child) {
            final screenHeight = MediaQuery.sizeOf(context).height;
            final scanY = _streamingAnimation.value * screenHeight;
            return Positioned(
              top: scanY,
              left: 0,
              right: 0,
              child: Container(
                height: 60,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      HexColor.fromHex('#79D2FF').withOpacity(0.01),
                      HexColor.fromHex('#79D2FF').withOpacity(0.2),
                      HexColor.fromHex('#79D2FF').withOpacity(0.7),
                    ],
                  ),
                ),
                child: Align(
                  alignment: Alignment.bottomCenter,
                  child: Container(
                    height: 3,
                    color: HexColor.fromHex('#00AAFF'),
                  ),
                ),
              ),
            );
          },
        ),
      ],
    );
  }
}

// --------------------------- UI helpers ---------------------------
class ScanClipper extends CustomClipper<Rect> {
  final double clipHeight;
  ScanClipper(this.clipHeight);

  @override
  Rect getClip(Size size) => Rect.fromLTRB(0, 0, size.width, clipHeight);

  @override
  bool shouldReclip(covariant ScanClipper oldClipper) =>
      oldClipper.clipHeight != clipHeight;
}

class _TimeoutSheet extends StatelessWidget {
  final VoidCallback? onCapture;
  final bool isTakingPicture;
  final String foot;
  const _TimeoutSheet({
    required this.onCapture,
    required this.isTakingPicture,
    required this.foot,
  });
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(left: 12, right: 12, top: 12),
      width: MediaQuery.sizeOf(context).width,
      height: MediaQuery.sizeOf(context).height * 0.15,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
      ),
      child: Column(children: [
        Text(
          'Failed to detect the $foot foot, please capture manually',
          style:
              Theme.of(context).textTheme.displaySmall!.copyWith(fontSize: 11),
        ),
        const SizedBox(height: 12),
        InkWell(
          onTap: onCapture,
          child: Center(
            child: CircleAvatar(
              radius: 32,
              backgroundColor: isTakingPicture
                  ? Colors.grey
                  : ColorManager.primaryBlue.withOpacity(0.5),
              child: isTakingPicture
                  ? const CircularProgressIndicator(color: Colors.white)
                  : CircleAvatar(
                      backgroundColor: ColorManager.primaryBlue, radius: 28),
            ),
          ),
        ),
      ]),
    );
  }
}

// Painter with rect caching (kept; not used now for preview)
class _OptimizedImagePainter extends CustomPainter {
  final ui.Image image;
  static ui.Image? _lastImage;
  static Rect? _lastSrcRect;
  static Rect? _lastDstRect;

  _OptimizedImagePainter(this.image);

  @override
  void paint(Canvas canvas, Size size) {
    if (size.width <= 0 || size.height <= 0) return;
    final imageW = image.width.toDouble();
    final imageH = image.height.toDouble();
    if (imageW <= 0 || imageH <= 0) return;

    final imageAspect = imageW / imageH;
    final canvasW = size.width;
    final canvasH = size.height;
    final canvasAspect = canvasW / canvasH;

    Rect srcRect;
    final dstRect = Rect.fromLTWH(0, 0, canvasW, canvasH);

    if (identical(image, _lastImage) && _lastSrcRect != null && _lastDstRect != null) {
      srcRect = _lastSrcRect!;
    } else {
      if (canvasAspect > imageAspect) {
        double srcH = imageW / canvasAspect;
        srcH = srcH.clamp(1.0, imageH);
        final top = ((imageH - srcH) / 2).clamp(0.0, imageH - srcH);
        srcRect = Rect.fromLTWH(0, top, imageW, srcH);
      } else {
        double srcW = imageH * canvasAspect;
        srcW = srcW.clamp(1.0, imageW);
        final left = ((imageW - srcW) / 2).clamp(0.0, imageW - srcW);
        srcRect = Rect.fromLTWH(left, 0, srcW, imageH);
      }
      _lastImage = image;
      _lastSrcRect = srcRect;
      _lastDstRect = dstRect;
    }

    if (srcRect.width > 0 && srcRect.height > 0) {
      try {
        canvas.drawImageRect(image, srcRect, dstRect, Paint());
      } catch (e) {
        debugPrint('Error drawing image rect: $e');
      }
    }
  }

  @override
  bool shouldRepaint(covariant _OptimizedImagePainter oldDelegate) =>
      oldDelegate.image != image;
}

// -------------------------------- Utility --------------------------------
Future<void> takePicture(
  BuildContext context,
  BluetoothNotifier bluetoothNotifier,
  String path,
  String foot,
  bool isLastFoot,
) async {
  try {
    final file = File(path);
    if (!await file.exists()) {
      throw Exception('Image file not found at path: $path');
    }

    final originalBytes = await file.readAsBytes();

    final dir = await getTemporaryDirectory();
    final fullPath =
        '${dir.path}/full_${DateTime.now().millisecondsSinceEpoch}.jpg';
    final fullImageFile = await File(fullPath).writeAsBytes(originalBytes);

    await bluetoothNotifier.executeFootPic(
      fullImageFile.path,
      foot,
      bluetoothNotifier.intakeFormParam ?? IntakeParam(),
    );

    if (context.mounted) {
      _showBottomSheet(context);

      await Future.delayed(const Duration(seconds: 2), () {
        if (context.mounted) {
          Provider.of<HomeNotifier>(context, listen: false).goToReview();
          if (isLastFoot) {
            navigatePushAndRemoveUntil(
                context: context, pageName: const HomePage());
          }
        }
      });
    }
  } catch (e) {
    debugPrint("Error in takePicture: $e");
    if (context.mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to save image: ${e.toString()}')),
      );
    }
  }
}

void _showBottomSheet(BuildContext context) {
  CustomBottomSheet.show(
    context: context,
    isDismissible: true,
    child: Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Center(
          child: Container(
            width: 50,
            height: 4,
            margin: const EdgeInsets.only(bottom: 20),
            decoration: BoxDecoration(
              color: Colors.grey.shade300,
              borderRadius: BorderRadius.circular(2),
            ),
          ),
        ),
        const SizedBox(height: 20),
        SvgPicture.asset(Assets.checkMarkIcon),
        Text(
          'Scan Complete',
          style: AppThemes.lightTheme.textTheme.displayMedium,
          textAlign: TextAlign.center,
        ),
        const SizedBox(height: 12),
        Text(
          Strings.verificationSentSMS,
          textAlign: TextAlign.center,
          style: AppThemes.lightTheme.textTheme.displaySmall!.copyWith(
            fontWeight: FontWeight.w500,
            letterSpacing: 0.4,
          ),
        ),
      ],
    ),
  );
}
Editor is loading...
Leave a Comment