import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

class TakePicturePage extends StatefulWidget {
  final CameraDescription camera;

  TakePicturePage({required this.camera});

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

class _TakePicturePageState extends State<TakePicturePage> {
  late CameraController _cameraController;
  Future<void>? _initializeCameraControllerFuture;

  @override
  void initState() {
    super.initState();
    _cameraController = CameraController(
      widget.camera,
      ResolutionPreset.medium,
    );
    initCamera();
  }

  void initCamera() async {
    try {
      // print(_cameraController.);
      _initializeCameraControllerFuture = _cameraController.initialize();
      // setState(() {});
    } catch (e) {
      print('catch $e');
      Navigator.pop(context);
      openAppSettings();
    }
  }

  @override
  void dispose() {
    _cameraController.dispose();
    super.dispose();
  }

  void _takePicture(BuildContext context) async {
    try {
      await _initializeCameraControllerFuture;
      var file = await _cameraController.takePicture();

      Navigator.pop(context, file.path);
    } catch (e) {
      print("take picture error:...$e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        // Flexible(
        //   fit: FlexFit.tight,
        //   child: Text('gdfgdf'),
        // ),
        // _initializeCameraControllerFuture == null
        //     ? SizedBox()
        //     : Flexible(
        //         fit: FlexFit.tight,
        //         child: FutureBuilder(
        //           future: _initializeCameraControllerFuture,
        //           builder: (context, snapshot) {
        //             if (snapshot.connectionState == ConnectionState.done) {
        //               return CameraPreview(_cameraController);
        //             } else {
        //               return Center(child: CircularProgressIndicator());
        //             }
        //           },
        //         ),
        //       ),
        Align(
          alignment: Alignment.bottomCenter,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: FloatingActionButton(
              backgroundColor: Colors.grey,
              child: Icon(Icons.camera, color: Colors.white),
              onPressed: () => _takePicture(context),
            ),
          ),
        )
      ],
    );
  }
}
