import json

from django.conf import settings
from django.test import SimpleTestCase
from django.test import override_settings
from django.test.client import RequestFactory
from mock.mock import patch
from rest_framework import status

from haso_payment.tests.mixins import MockResponseMixin

try:
    settings.configure()
except RuntimeError:
    pass


@override_settings(
    PZ_SERVICE_CLASS="haso_payment.commerce.dummy.Service",
    HASO_EXTENSION_CONF={
        "default": {
            "extension_url": "https://your-extension.url",
            "hash_key": "your-extension-hash-key",
        }
    }
)
class TestCheckoutService(SimpleTestCase, MockResponseMixin):
    def setUp(self):
        from haso_payment.commerce.checkout import CheckoutService

        self.service = CheckoutService()
        self.request_factory = RequestFactory()

    @patch("haso_payment.commerce.dummy.Service.get")
    @patch("haso_payment.helpers.generate_hash")
    @patch("haso_payment.helpers.generate_salt")
    def test_get_data(self, mock_generate_salt, mock_generate_hash, mock_get):
        mock_generate_hash.return_value = "test-hash"
        mock_generate_salt.return_value = "test-salt"
        mocked_response = self._mock_response(
            status_code=200,
            content=self._get_response("orders_checkout_response"),
            headers={"Content-Type": "application/json"},
        )
        mock_get.return_value = mocked_response

        request = self.request_factory.get("/payment-gateway/haso/")
        extension_url, form_data = self.service.get_form_data(request)
        if isinstance(form_data, (bytes, bytearray)):
            form_data = form_data.decode("utf-8")
        if isinstance(form_data, str):
            form_data = json.loads(form_data)

        self.assertEqual(form_data["salt"], "test-salt")
        self.assertEqual(form_data["hash"], "test-hash")

        address = form_data["shipping_address"]
        self.assertEqual(
            set(address.keys()), {
                "first_name", "last_name", "phone_number", "line", "district",
                "township", "city", "country", "zip_code"
            }
        )
        self.assertEqual(address["first_name"], "akinon")
        self.assertEqual(address["last_name"], "akinon")
        self.assertEqual(address["phone_number"], "0555555555")
        self.assertEqual(
            address["line"],
            "YTÜ-Davutpaşa Kampüsü Teknopark Bölgesi "
            "B2 Blok D:Kat:2, No: 417"
        )
        self.assertEqual(address["district"], "ÇİFTEHAVUZLAR/ESENLER")
        self.assertEqual(address["township"], "ESENLER")
        self.assertEqual(address["city"], "İstanbul")
        self.assertEqual(address["country"], "TR")
        self.assertEqual(address["zip_code"], "34220")

    @patch("haso_payment.commerce.dummy.Service.get")
    def test_retrieve_pre_oder(self, mock_get):
        mocked_response = self._mock_response(
            status_code=200,
            content=self._get_response("orders_checkout_response"),
            headers={"Content-Type": "application/json"},
        )
        mock_get.return_value = mocked_response

        request = self.request_factory.get("/payment-gateway/haso/")
        response = self.service._retrieve_pre_order(request)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn("pre_order", response.data)

    def test_shipping_address(self):
        _shipping_address = self.service._get_shipping_address({
            "pk": 50,
            "email": "akinon@akinon.com",
            "phone_number": "0555555555",
            "first_name": "akinon",
            "last_name": "akinon",
            "country": {
                "pk": 1,
                "name": "Türkiye",
                "code": "tr"
            },
            "city": {
                "pk": 47,
                "name": "İstanbul",
                "country": 1
            },
            "line": "YTÜ-Davutpaşa Kampüsü Teknopark Bölgesi "
                    "B2 Blok D:Kat:2, No: 417",
            "title": "ofis",
            "township": {
                "pk": 209,
                "name": "ESENLER",
                "city": 47
            },
            "district": {
                "pk": 2194,
                "name": "ÇİFTEHAVUZLAR/ESENLER",
                "city": 47,
                "township": 209
            },
            "postcode": "34220",
            "notes": None,
            "company_name": "",
            "tax_office": "",
            "tax_no": "",
            "e_bill_taxpayer": False,
            "is_corporate": False,
            "primary": False,
            "identity_number": None,
            "extra_field": None
        })
        self.assertEqual(
            _shipping_address,
            {
                "first_name": "akinon",
                "last_name": "akinon",
                "phone_number": "0555555555",
                "line": "YTÜ-Davutpaşa Kampüsü Teknopark Bölgesi "
                        "B2 Blok D:Kat:2, No: 417",
                "district": "ÇİFTEHAVUZLAR/ESENLER",
                "township": "ESENLER",
                "city": "İstanbul",
                "country": "TR",
                "zip_code": "34220",
            }
        )
