import 'dart:convert';
import 'dart:io';
import 'package:initial_folder/base_service.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/models/profile_image_post_model.dart';
import 'package:http/http.dart' as http;

class ProfileImageService {
  Future<ProfileImagePostModel> addProfileImage({required File pckFile}) async {
    int? idUser = await UsersInfo().getIdUser();
    Uri url = Uri.parse('$baseUrl/users/profile/user-photo/$idUser');
    String? token = await UsersInfo().getToken();

    var req = http.MultipartRequest('POST', url);
    req.headers.addAll(headerWithToken(token!));
    req.files.add(http.MultipartFile(
        'foto_profile', pckFile.readAsBytes().asStream(), pckFile.lengthSync(),
        filename: pckFile.path.split("/").last));

    var streamed = await req.send();
    var response = await http.Response.fromStream(streamed);
    print('Ini file gambar nya ${pckFile.path.split("/").last}');
    print(response.body);
    if (response.statusCode == 201 || response.statusCode == 200) {
      return ProfileImagePostModel.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Gagal Mengganti Foto Profil');
    }
  }
}
