import 'package:geolocator/geolocator.dart';

import '../common/settings.dart';


class WaterSuppliersModel {

  String supplier_name = '';
  String status = '';
  String supplier_address = '';
  String supplier_phone_number = '';
  String supplier_alternate_phone_number = '';
  String supplier_id = '';
  String about_supplier = '';
  String startingprice_supplier = '';

  double lat = 0;
  double lng = 0;

  double distanceInMeters = 0;

  String displayAddress = '';

  bool isFavorite = false;
  bool isConnected = false;

  WaterSuppliersModel();

  factory WaterSuppliersModel.fromJson(Map<String, dynamic> json) {

    WaterSuppliersModel rtvm = WaterSuppliersModel();

    var supplier = json['supplier'];

    rtvm.supplier_name = supplier['suppliername'] ?? '';

    rtvm.status = supplier['status'] ?? '';

    rtvm.supplier_address =
        supplier['profile']?['office_address'] ?? '';

    rtvm.supplier_phone_number =
        supplier['phone'] ?? '';

    rtvm.supplier_alternate_phone_number =
        supplier['profile']?['alternativeContactNumber'] ?? '';

    rtvm.supplier_id =
        supplier['supplierId'] ?? '';

    rtvm.lat =
        (supplier['latitude'] ?? 0).toDouble();

    rtvm.lng =
        (supplier['longitude'] ?? 0).toDouble();

    rtvm.about_supplier =
        supplier['description'] ?? '';

    rtvm.startingprice_supplier =
        supplier['startingPrice'] ?? '';

    rtvm.isFavorite =
        json['isFavorite'] ?? false;

    rtvm.isConnected =
        json['isConnected'] ?? false;

    try {

      rtvm.distanceInMeters = double.parse(
        (Geolocator.distanceBetween(
            rtvm.lat,
            rtvm.lng,
            AppSettings.userLatitude,
            AppSettings.userLongitude) /
            1000)
            .toStringAsFixed(2),
      );

    } catch (e) {

      rtvm.distanceInMeters = 0;

    }

    /// Address safe parsing

    if (rtvm.supplier_address.contains(',')) {

      List<String> parts = rtvm.supplier_address.split(',');

      if (parts.length > 2) {
        rtvm.displayAddress = parts[2].trim();
      } else {
        rtvm.displayAddress = parts.last.trim();
      }

    } else {

      rtvm.displayAddress = rtvm.supplier_address;

    }

    return rtvm;
  }

}