from django.test import TestCase

from .forms import PropertyLocationForm


class PropertyLocationFormTests(TestCase):
    def test_address_overrides_browser_location(self):
        form = PropertyLocationForm(
            data={
                "address": "123 Main St, Madrid",
                "latitude": "40.416800",
                "longitude": "-3.703800",
                "phone": "",
                "email": "",
                "listing_type": "unknown",
                "idealista_url": "",
            }
        )

        self.assertTrue(form.is_valid(), form.errors)
        self.assertIsNone(form.cleaned_data["latitude"])
        self.assertIsNone(form.cleaned_data["longitude"])
        self.assertEqual(form.cleaned_data["address"], "123 Main St, Madrid")

    def test_browser_location_is_kept_when_no_address_is_entered(self):
        form = PropertyLocationForm(
            data={
                "address": "",
                "latitude": "40.416800",
                "longitude": "-3.703800",
                "phone": "",
                "email": "",
                "listing_type": "unknown",
                "idealista_url": "",
            }
        )

        self.assertTrue(form.is_valid(), form.errors)
        self.assertIsNotNone(form.cleaned_data["latitude"])
        self.assertIsNotNone(form.cleaned_data["longitude"])

    def test_address_or_location_is_required(self):
        form = PropertyLocationForm(
            data={
                "address": "",
                "latitude": "",
                "longitude": "",
                "phone": "",
                "email": "",
                "listing_type": "unknown",
                "idealista_url": "",
            }
        )

        self.assertFalse(form.is_valid())
        self.assertIn("__all__", form.errors)
