import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SendFile extends StatefulWidget {
  const SendFile({super.key});

  @override
  State<SendFile> createState() => _SendFileState();
}

class _SendFileState extends State<SendFile> {
  File? pickedFile;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          ElevatedButton(
              onPressed: () async {
                FilePickerResult? result =
                    await FilePicker.platform.pickFiles();

                if (result != null) {
                  pickedFile = File(result.files.single.path!);
                } else {
                  pickedFile = File("");
                }
              },
              child: Text(AppLocalizations.of(context)!.pickfile)),
          Text(pickedFile.toString()),
          ElevatedButton(
              onPressed: () async {
                final dio = Dio();
                final SharedPreferences prefs =
                    await SharedPreferences.getInstance();
                String? fileContent = await pickedFile?.readAsString();

                dio.options.responseType = ResponseType.plain;
                Response response = Response(
                    requestOptions: RequestOptions(path: ''), statusCode: 400);

                try {
                  response = await dio.post(prefs.getString('apiAddress') ?? "",
                      data: jsonEncode(fileContent));
                } on DioException catch (e) {
                  if (e.response?.statusCode == 500) {
/*         print('-------------------------');
        print('code 500'); */
                    return;
                  }
                }
                if (response.statusCode == 201) {
                  // print(response.statusCode);
                } else {
                  //print(response.statusCode);
                }
              },
              child: Text(AppLocalizations.of(context)!.sendtoserver))
        ],
      ),
    );
  }
}
