import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tflite/tflite.dart';

// severityLevelDetectionState
class SeverityLevelDetection extends StatefulWidget {
  const SeverityLevelDetection({Key? key}) : super(key: key);

  @override
  State<SeverityLevelDetection> createState() => _severityLevelDetectionState();
}

class _severityLevelDetectionState extends State<SeverityLevelDetection> {

  late File pickedImage;
  bool _busy = false;
  late List _recognitions;
  bool isImageLoaded = false;
  late List resultList;
  String _confidence = "";
  String _name = "";
  String numbers = "";

  getImageFromGallery() async {
    var image =
    await ImagePicker.platform.getImage(source: ImageSource.gallery);
    print("11111:");
    setState(() {
      _busy = true;
    });

    pickedImage = File(image!.path);
    isImageLoaded = true;
    predictImage(pickedImage);
  }

  getImageFromCamera() async {
    var image = await ImagePicker.platform.getImage(source: ImageSource.camera);
    setState(() {
      _busy = true;
    });

    pickedImage = File(image!.path);
    isImageLoaded = true;
    predictImage(pickedImage);
  }

  void predictImage(File image) async {
    await applyModelOnImage(image);
  }

  loadDetectionModel() async {
    try {
      String? res = await Tflite.loadModel(
          model: "assets/severitymodel.tflite",
          labels: "assets/levels-s.txt",
          numThreads: 1,
          // defaults to 1
          isAsset: true,
          // defaults to true, set to false to load resources outside assets
          useGpuDelegate:
          false // defaults to false, set to true to use GPU delegate
      );
      print("Model Result : $res");
    } on PlatformException {
      print('Failed to load model.');
    }
  }

  applyModelOnImage(File image) async {
    int startTime = new DateTime.now().millisecondsSinceEpoch;

    var recognitions = await Tflite.runModelOnImage(
        path: image.path,
        // required
        imageMean: 0.0,
        // defaults to 117.0
        imageStd: 255.0,
        // defaults to 1.0
        numResults: 2,
        // defaults to 5
        threshold: 0.2,
        // defaults to 0.1
        asynch: true // defaults to true
    );
    setState(() {
      _recognitions = recognitions!;
      print("res result : $_recognitions");
      String str = _recognitions[0]["label"];
      _name = str.substring(2);
      print("Detected Levels: $_name");
      _confidence = _recognitions != null
          ? (_recognitions[0]["confidence"] * 100.0)
          .toString()
          .substring(0, 2) +
          "%"
          : "";
      print("Confidence: $_confidence");
    });
    int endTime = new DateTime.now().millisecondsSinceEpoch;
    print("Inference took ${endTime - startTime}ms"); // setState(() {
  }

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

  void objectRecocnition() async {}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text("Severity Level Detection")),
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                  padding: const EdgeInsets.only(
                    left: 20,

                    right: 20,
                    top: 35,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            SizedBox(height: 350),
                            isImageLoaded
                                ? Center(
                              child: Container(
                                height: 350,
                                width: 350,
                                decoration: BoxDecoration(
                                    image: DecorationImage(
                                        image: FileImage(
                                            File(pickedImage.path)),
                                        fit: BoxFit.contain)),
                              ),
                            )
                                : Container(),
                          ]),
                      Padding(
                          padding: const EdgeInsets.only(
                            left: 20,
                            right: 20,
                            top: 100,
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                  "Identified Severity Level: $_name \n Confidence: $_confidence"
                                // style: TextStyle(
                                //   color: Color(0xFFF05A22),
                                //   fontFamily: 'Montserrat',
                                //   fontSize: 16,
                                //   fontWeight: FontWeight.w600,
                                //   letterSpacing: 1,
                                // ),
                              ),
                              Row(
                                  mainAxisAlignment:
                                  MainAxisAlignment.spaceBetween,
                                  children: [
                                    SizedBox(
                                      width: 331.4,
                                      height: 50.0,
                                      child: GestureDetector(
                                        onTap: () {
                                          getImageFromGallery();
                                        },
                                        child: Container(
                                          // padding: EdgeInsets.fromLTRB(20, 30, 10, 15),
                                          decoration: BoxDecoration(
                                            border: Border.all(
                                              // color: const Color(0xFFF05A22),
                                              style: BorderStyle.none,
                                              width: 1.0,
                                            ),
                                            color: Colors.blue[200],
                                            borderRadius:
                                            BorderRadius.circular(10.0),
                                          ),
                                          child: Row(
                                            mainAxisAlignment:
                                            MainAxisAlignment.center,
                                            children: const <Widget>[
                                              Center(
                                                child: Text(
                                                  "Launch Gallery",
                                                  style: TextStyle(
                                                    color: Color(0xFFFFFFFF),
                                                    fontFamily: 'Montserrat',
                                                    fontSize: 16,
                                                    fontWeight: FontWeight.w600,
                                                    letterSpacing: 1,
                                                  ),
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                      ),
                                    ),
                                  ]),
                              Padding(
                                padding: const EdgeInsets.only(
                                  // left: 20,
                                  // right: 20,
                                  top: 30,
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Row(
                                        mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                        children: [
                                          SizedBox(
                                            width: 331.4,
                                            height: 50.0,
                                            child: GestureDetector(
                                              onTap: () {
                                                getImageFromCamera();
                                              },
                                              child: Container(
                                                // padding: EdgeInsets.fromLTRB(20, 30, 10, 15),
                                                decoration: BoxDecoration(
                                                  border: Border.all(
                                                    // color: const Color(0xFFF05A22),
                                                    style: BorderStyle.none,
                                                    width: 1.0,
                                                  ),
                                                  color: Colors.blue[200],
                                                  borderRadius:
                                                  BorderRadius.circular(
                                                      10.0),
                                                ),
                                                child: Row(
                                                  mainAxisAlignment:
                                                  MainAxisAlignment.center,
                                                  children: const <Widget>[
                                                    Center(
                                                      child: Text(
                                                        "Take a Picture ",
                                                        style: TextStyle(
                                                          color:
                                                          Color(0xFFFFFFFF),
                                                          fontFamily:
                                                          'Montserrat',
                                                          fontSize: 16,
                                                          fontWeight:
                                                          FontWeight.w600,
                                                          letterSpacing: 1,
                                                        ),
                                                      ),
                                                    )
                                                  ],
                                                ),
                                              ),
                                            ),
                                          ),
                                        ]),
                                  ],
                                ),
                              ),
                            ],
                          )),
                    ],
                  )),
            ],
          ),
        ));
  }
}
