import 'dart:math';

import '../globals.dart';

class LocationData {
  final String name;

  final double latitude;

  final double longitude;

  final double altitude;

  final bool hasPosition;

  final String address;

  final String url;

  const LocationData(
      {this.name = '',
      this.latitude = 0.0,
      this.longitude = 0.0,
      this.altitude = 0.0,
      this.hasPosition = false,
      this.address = '',
      this.url = ''});

  LocationData.randomBuilt()
      : name = 'Location name ${randomId()}',
        latitude = Random().nextDouble(),
        longitude = Random().nextDouble(),
        altitude = Random().nextDouble(),
        hasPosition = true,
        address = 'Address ${randomId()}',
        url = 'http://localhost/${randomId()}';

  @override
  String toString() {
    return 'LocationData{name: $name, latitude: $latitude, longitude: $longitude, altitude: $altitude, hasPosition: $hasPosition, address: $address, url: $url}';
  }

  String toHumanString() {
    if (!hasPosition) {
      return '';
    }

    return [
      if (name.isNotEmpty) 'Name: $name',
      if (address.isNotEmpty) 'Address: $address',
      'Latitude: $latitude',
      'Longitude: $longitude',
    ].join('\n');
  }

  bool hasData() =>
      name.isNotEmpty || address.isNotEmpty || url.isNotEmpty || hasPosition;

  static LocationData fromJson(Map<String, dynamic> json) {
    final name = json['name'] ?? '';
    final address = json['address'] ?? '';
    final url = json['url'] ?? '';
    var latitude = 0.0;
    var longitude = 0.0;
    var altitude = 0.0;
    var hasPosition = json.containsKey('coordinate');
    if (hasPosition) {
      final position = json['coordinate'];
      latitude = position['latitude'] ?? 0.0;
      longitude = position['longitude'] ?? 0.0;
      altitude = position['altitude'] ?? 0.0;
    }

    return LocationData(
        name: name,
        address: address,
        url: url,
        hasPosition: hasPosition,
        latitude: latitude,
        longitude: longitude,
        altitude: altitude);
  }
}
