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

import 'package:http/http.dart' as http;
import 'package:unit2/model/passo/structural_materials_ii.dart';
import 'package:unit2/model/passo/structureMaterial.dart';
import 'package:unit2/utils/request.dart';
import 'package:unit2/utils/urls.dart';

class StrucMaterialServices {
  static final StrucMaterialServices _instance = StrucMaterialServices();
  static StrucMaterialServices get instance => _instance;

  String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z";
  String xClientKeySecret = "unitcYqAN7GGalyz";

  Future<http.Response?> update(StructureMaterialsII data, id) async {
    String path = Url.instance.structuralMaterials();
    Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      'X-Client-Key': xClientKey,
      'X-Client-Secret': xClientKeySecret
    };
    Map<String, String> params = {
      "bldgappr_details_id": id.toString(),
    };
    http.Response? response;
    try {
      response = await Request.instance.putRequest(
          path: path, body: data.toJson(), headers: headers, param: params);
    } catch (e) {
      log(e.toString());
    }
    return response;
  }

  Future<StructureMaterials> fetch(id) async {
    String path = Url.instance.structuralMaterials();
    Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      'X-Client-Key': xClientKey,
      'X-Client-Secret': xClientKeySecret
    };
    Map<String, String> params = {
      "bldgappr_details_id": id.toString(),
    };
    try {
      http.Response response = await Request.instance
          .getRequest(param: params, path: path, headers: headers);
      print('StructureMaterialsII');
      print(response.body);
      if (response.statusCode == 200) {
        final jsonData = jsonDecode(response.body);
        final dataList = jsonData['data'] as List<dynamic>;
        final result =
            StructureMaterials.fromJson(dataList[0] as Map<String, dynamic>);

        return result;
      } else {
        throw Exception(response.reasonPhrase);
      }
    } catch (e) {
      throw e.toString();
    }
  }
}
