import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:path/path.dart';
import 'package:project_manager/consts.dart';


class Documents{
  static Future<File?> pickDocument() async {
    File? document;
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['xlsx', 'xls'],
    );
      if (result != null) {
        document = File(result.files.single.path!);
      }
    return document;
  }

  static Future<bool> uploadDocument(File? document) async {
    if (document == null) {
      print('No file to upload!');
      return false;
    }

    var uri = Uri.parse("$URI/deliveries/upload");
    List<int>? excelBytes = document?.readAsBytesSync().toList();
    var request = http.MultipartRequest('POST', uri)
      ..files.add(http.MultipartFile.fromBytes(
        'file',
        excelBytes!,
        filename: basename(document!.path),
        contentType: MediaType('application',
            'vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
      ));
    var response = await request.send();
    if (response.statusCode == 201) {
      print('Uploaded successfully');
      return true;
    } else {
      print('Upload failed.\nReason: ${response.reasonPhrase}');
      return false;
    }
  }
}