import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import './image_picker_dialog.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';

class ImagePickerHandler {
  late ImagePickerDialog imagePicker;
  AnimationController _controller;
  ImagePickerListener _listener;

  ImagePickerHandler(this._listener, this._controller);

  late ImagePicker imPick;

  openCamera() async {
    imagePicker.dismissDialog();
    var image = await imPick.pickImage(source: ImageSource.camera);
    cropImage(image!);
  }

  openGallery() async {
    imagePicker.dismissDialog();
    var image = await imPick.pickImage(source: ImageSource.gallery);
    cropImage(image!);
  }

  void init() {
    imPick = ImagePicker();
    imagePicker = ImagePickerDialog(this, _controller);
    imagePicker.initState();
  }

  Future cropImage(XFile image) async {
    var ci = ImageCropper();
    File? croppedFile = await ci.cropImage(
      sourcePath: image.path,
      aspectRatioPresets: <CropAspectRatioPreset>[CropAspectRatioPreset.square],
      maxWidth: 512,
      maxHeight: 512,
    );
    _listener.userImage(croppedFile!);
  }

  showDialog(BuildContext context) {
    imagePicker.getImage(context);
  }
}

abstract class ImagePickerListener {
  userImage(File _image);
}
