import 'dart:convert';
import 'dart:io';

import 'package:flutter_tesseract_ocr/flutter_tesseract_ocr.dart';
import 'package:get/get.dart';
import 'package:google_mlkit_text_recognition/google_mlkit_text_recognition.dart';
import 'package:image_picker/image_picker.dart';

class OCRController extends GetxController {
  final text = RxString('');

  void setText(value) {
    text.value = value;
  }
}

class TextExtractionController extends GetxController {
  String extractedText = '';
  bool isloading = false;
  File? _scannedImage;
// Convert the extracted text to JSON
  String getTextAsJSON(String text) {
    final json = {
      'text': text,
      'num_lines': text.split('\n').length,
    };

    return jsonEncode(json);
  }

// Convert the extracted text to blocks by line
  List<String> getTextBlocks(String text) {
    return text.split('\n');
  }

  Future<void> pickAndExtractText() async {
    final pickedImage = await ImagePicker().pickImage(
      source: ImageSource.camera,
      preferredCameraDevice: CameraDevice.rear,
      maxHeight: Get.height * .7,
      maxWidth: Get.width * .9,
      imageQuality: 99,
    );
    if (pickedImage != null) {
      isloading = true;
      update();
      final imagePath = pickedImage.path;
      final languages = [
        'eng',
        'ara'
      ]; // Specify the languages you want to use for text extraction

      try {
        final text = await FlutterTesseractOcr.extractText(imagePath,
            language:
                languages.join('+'), // Combine multiple languages with '+'
            args: {
              "psm": "4",
              "preserve_interword_spaces":
                  "1", // "rectangle": Rect.fromLTWH(100, 100, 200, 200),
            } // Additional options if needed
            );
        isloading = false;
        final jsonText = getTextAsJSON(text);
        final textBlocks = getTextBlocks(text);
        update();
        extractedText =
            textBlocks.toString(); // Convert the extracted text to JSON.

// Print the JSON to the console.
        print(jsonText);
        update();
        // print(text);
      } catch (e) {
        print('Error during text extraction: $e');
        extractedText = '';
      }
    }
  }
}

class TextMLGoogleRecognizerController extends GetxController {
  @override
  void onInit() {
    scanText();
    super.onInit();
  }

  // The ImagePicker instance
  final ImagePicker _imagePicker = ImagePicker();

  // The GoogleMlKit TextRecognizer instance
  final TextRecognizer _textRecognizer = TextRecognizer();

  // The scanned text
  String? scannedText;

  // Picks an image from the camera or gallery and extracts the text

  Future<void> scanText() async {
    // Pick an image from the camera or gallery
    final XFile? image =
        await _imagePicker.pickImage(source: ImageSource.camera);

    // If no image was picked, return
    if (image == null) {
      return;
    }

    // Convert the XFile object to an InputImage object
    final InputImage inputImage = InputImage.fromFile(File(image.path));

    // Recognize the text in the image
    final RecognizedText recognizedText =
        await _textRecognizer.processImage(inputImage);
    scannedText = recognizedText.text;
    // Extract the scanned text line by line
    final List<Map<String, dynamic>> lines = [];
    for (var i = 0; i < recognizedText.blocks.length; i++) {
      lines.add({
        'line_number': i,
        'text': recognizedText.blocks[i].text,
      });
    }

    // Convert the list of lines to a JSON string
    final String jsonOutput = jsonEncode(lines);
    update();
    // Print the JSON output
    print(jsonOutput);
  }
}
