import pickle
import pytest
import os
from unittest.mock import Mock
from recommendations.FloorRecommendations import FloorRecommendations
from recommendations.tests.test_data.materials import materials
from backend.Property import Property
from etl.epc.Record import EPCRecord


# import inspect
#
# file_path = inspect.getfile(lambda: None)
# with open(
#     os.path.abspath(os.path.dirname(file_path)) + "/recommendations/tests/test_data/input_properties.pkl", "rb"
# ) as f:
#     input_properties = pickle.load(f)


class TestFloorRecommendations:

    def test_init(self):
        p = Mock()
        p.epc_record = Mock()
        p.epc_record.county = "Greater London"
        p.epc_record.local_authority_label = "London"
        p.epc_record.insulation_floor_area = 50
        p.epc_record.insulation_wall_area = 90
        p.insulation_floor_area = 50
        p.insulation_wall_area = 90
        p.floor = {"another_property_below": False}
        obj = FloorRecommendations(
            property_instance=p,
            materials=materials
        )
        assert obj
        assert obj.property

    def test_other_premises_below(self):
        p = Mock()
        p.epc_record = Mock()
        p.epc_record.county = "Greater London"
        p.epc_record.local_authority_label = "London"
        p.epc_record.insulation_floor_area = 100
        p.epc_record.insulation_wall_area = 999
        p.insulation_floor_area = 100
        p.insulation_wall_area = 999
        p.number_of_floors = 1
        p.floor = {"another_property_below": True, "thermal_transmittance": None, "insulation_thickness": None}
        recommender = FloorRecommendations(
            property_instance=p,
            materials=materials
        )
        recommender.recommend()
        assert recommender.property.floor["another_property_below"]

        assert not recommender.recommendations

    def test_suspended_no_insulation(self):
        """
        For a suspended floor without insulation, we use the rdsap methogology to estimate a U-value for the floor
        :return:
        """
        p = Mock()
        p.epc_record = Mock()
        p.epc_record.county = "Greater London"
        p.epc_record.local_authority_label = "London"
        p.epc_record.insulation_floor_area = 50
        p.epc_record.insulation_wall_area = 50
        p.insulation_floor_area = 50
        p.insulation_wall_area = 50
        p.walls = {"is_park_home": False}
        p.age_band = "A"
        p.perimeter = 20
        p.wall_type = "solid brick"
        p.floor_type = "suspended"
        p.number_of_floors = 1
        p.floor_level = 0
        p.already_installed = []
        p.non_invasive_recommendations = {}
        p.floor = {
            "is_suspended": True,
            "is_solid": False,
            "another_property_below": False,
            "thermal_transmittance": None,
            "insulation_thickness": None,
            "thermal_transmittance_unit": None,
            "is_assumed": False,
            "is_to_unheated_space": False,
            "is_to_external_air": False,
        }
        p.full_sap_epc = {}
        recommender = FloorRecommendations(property_instance=p, materials=materials)
        assert recommender.estimated_u_value is None
        recommender.recommend()
        assert recommender.property.floor["is_suspended"]
        assert recommender.estimated_u_value == 0.66
        assert recommender.recommendations

        types = {part["type"] for x in recommender.recommendations for part in x["parts"]}

        assert types == {"suspended_floor_insulation"}

        assert len(recommender.recommendations) == 1
        assert recommender.recommendations[0]["total"] == 4687.5
        assert recommender.recommendations[0]["new_u_value"] == 0.21

    def test_uvalue_0_12(self):
        """
        This is a home that doesn't have a property below but it's highly performant already and therefore
        does not need floor insulation
        :return:
        """
        p = Mock()
        p.epc_record = Mock()
        p.epc_record.county = "Greater London"
        p.epc_record.local_authority_label = "London"
        p.epc_record.insulation_floor_area = 100
        p.epc_record.insulation_wall_area = 100
        p.insulation_floor_area = 100
        p.insulation_wall_area = 100
        p.number_of_floors = 1
        p.floor_level = 0
        p.floor = {
            "is_suspended": False,
            "is_solid": False,
            "another_property_below": False,
            "thermal_transmittance": 0.12,
            "insulation_thickness": None,
            "is_to_unheated_space": False,
            "is_to_external_air": False,
        }
        p.full_sap_epc = {}
        recommender = FloorRecommendations(property_instance=p, materials=materials)
        assert recommender.estimated_u_value is None
        recommender.recommend()
        assert not recommender.property.floor["is_suspended"]
        assert not recommender.property.floor["is_solid"]
        assert recommender.estimated_u_value is None
        assert not recommender.recommendations

    def test_solid_no_insulation(self):
        """
        :return:
        """
        p = Mock()
        p.epc_record = Mock()
        p.epc_record.county = ""
        p.epc_record.local_authority_label = "London"
        p.epc_record.insulation_floor_area = 100
        p.epc_record.insulation_wall_area = 100
        p.insulation_floor_area = 100
        p.insulation_wall_area = 100
        p.walls = {"is_park_home": False}
        p.age_band = "B"
        p.perimeter = 50
        p.wall_type = "solid brick"
        p.floor_type = "solid"
        p.number_of_floors = 1
        p.floor_level = 0
        p.already_installed = []
        p.non_invasive_recommendations = {}
        p.data = {"county": ""}
        p.floor = {
            "is_suspended": False,
            "is_solid": True,
            "another_property_below": False,
            "thermal_transmittance": None,
            "insulation_thickness": None,
            "is_to_unheated_space": False,
            "is_to_external_air": False,
            "thermal_transmittance_unit": None,
            "is_assumed": True,
        }
        p.full_sap_epc = {}
        recommender = FloorRecommendations(property_instance=p, materials=materials)
        assert recommender.estimated_u_value is None
        recommender.recommend()
        assert not recommender.property.floor["is_suspended"]
        assert recommender.property.floor["is_solid"]
        assert recommender.estimated_u_value == 0.73
        assert recommender.recommendations

        types = {part["type"] for x in recommender.recommendations for part in x["parts"]}

        assert types == {"solid_floor_insulation"}

        assert len(recommender.recommendations) == 1
        assert (
            recommender.recommendations[0]["description"] ==
            'Install 75mm Kingspan Thermafloor TF70 High Performance Rigid Floor '
            'Insulation insulation on solid floor'
        )

        assert recommender.recommendations[0]["new_u_value"] == 0.21
        assert recommender.recommendations[0]["simulation_config"] == {
            'floor_is_assumed_ending': False, 'floor_insulation_thickness_ending': 'average',
            'floor_thermal_transmittance_ending': 0.685593
        }
        assert recommender.recommendations[0]["description_simulation"] == {
            'floor-description': 'Solid, insulated'
        }

    def test_another_dwelling_below(self):
        """
        This is another description we see when there is a property below
        """
        p = Mock()
        p.epc_record = Mock()
        p.epc_record.county = "Greater London"
        p.epc_record.local_authority_label = "London"
        p.epc_record.insulation_floor_area = 100
        p.epc_record.insulation_wall_area = 1
        p.insulation_floor_area = 100
        p.insulation_wall_area = 1
        p.number_of_floors = 1
        p.floor = {
            "is_suspended": False,
            "is_solid": False,
            "another_property_below": True,
            "thermal_transmittance": None,
            "insulation_thickness": None,
        }
        recommender = FloorRecommendations(property_instance=p, materials=materials)
        assert recommender.estimated_u_value is None
        recommender.recommend()
        assert not recommender.property.floor["is_suspended"]
        assert not recommender.property.floor["is_solid"]
        assert recommender.estimated_u_value is None
        assert not recommender.recommendations

    def test_exposed_floor_no_insulation(self):
        epc_record = EPCRecord()
        epc_record.county = "Greater London"
        epc_record.floor_level = "0"
        epc_record.property_type = "House"
        epc_record.full_sap_epc = {}

        input_property = Property(id=1, postcode="F4k3 2", address="223 fake street", epc_record=epc_record)
        input_property.floor = {
            'original_description': 'To unheated space, no insulation (assumed)',
            'clean_description': 'To unheated space, no insulation', 'thermal_transmittance': None,
            'thermal_transmittance_unit': None, 'is_assumed': True, 'is_to_unheated_space': True,
            'is_to_external_air': False, 'is_suspended': False, 'is_solid': False, 'another_property_below': False,
            'insulation_thickness': 'none'
        }
        input_property.age_band = "L"
        input_property.set_floor_type()
        input_property.floor_area = 100
        input_property.number_of_floors = 1
        input_property.already_installed = []

        recommender = FloorRecommendations(
            property_instance=input_property,
            materials=materials
        )

        assert not recommender.recommendations

        recommender.recommend()

        # Because of age band L, this should have a u-value of 0.22 to begin with and no recommendation
        assert not len(recommender.recommendations)
        assert recommender.estimated_u_value == 0.22

        # Now with an older age band
        epc_record2 = EPCRecord()
        epc_record2.county = "Greater London"
        epc_record2.floor_level = "0"
        epc_record2.property_type = "House"
        epc_record2.full_sap_epc = {}

        input_property2 = Property(id=1, postcode="F4k3 2", address="223 fake street", epc_record=epc_record2)
        input_property2.floor = {
            'original_description': 'To unheated space, no insulation (assumed)',
            'clean_description': 'To unheated space, no insulation', 'thermal_transmittance': None,
            'thermal_transmittance_unit': None, 'is_assumed': True, 'is_to_unheated_space': True,
            'is_to_external_air': False, 'is_suspended': False, 'is_solid': False, 'another_property_below': False,
            'insulation_thickness': 'none'
        }
        input_property2.age_band = "D"
        input_property2.set_floor_type()
        input_property2.insulation_floor_area = 100
        input_property2.number_of_floors = 1
        input_property2.already_installed = []

        recommender2 = FloorRecommendations(
            property_instance=input_property2,
            materials=materials
        )

        assert not recommender2.recommendations

        recommender2.recommend()

        assert len(recommender2.recommendations) == 1

        assert recommender2.recommendations[0]["new_u_value"] == 0.24
        assert recommender2.recommendations[0]["starting_u_value"] == 1.2
        assert recommender2.recommendations[0]["total"] == 9375

    def test_exposed_floor_below_average_insulated(self):
        epc_record3 = EPCRecord()
        epc_record3.county = "Greater London"
        epc_record3.floor_level = "0"
        epc_record3.property_type = "House"
        epc_record3.full_sap_epc = {}
        input_property3 = Property(id=1, postcode="F4k3 2", address="223 fake street", epc_record=epc_record3)
        input_property3.floor = {
            'original_description': 'To unheated space, below average insulation (assumed)',
            'clean_description': 'To unheated space, below average insulation', 'thermal_transmittance': None,
            'thermal_transmittance_unit': None, 'is_assumed': True, 'is_to_unheated_space': True,
            'is_to_external_air': False, 'is_suspended': False, 'is_solid': False, 'another_property_below': False,
            'insulation_thickness': 'below average'
        }
        input_property3.age_band = "C"
        input_property3.set_floor_type()
        input_property3.insulation_floor_area = 100
        input_property3.number_of_floors = 1
        input_property3.already_installed = []

        recommender3 = FloorRecommendations(
            property_instance=input_property3,
            materials=materials
        )

        assert not recommender3.recommendations

        recommender3.recommend()

        assert recommender3.estimated_u_value == 0.5

        assert len(recommender3.recommendations) == 1

        assert recommender3.recommendations[0]["new_u_value"] == 0.24
        assert recommender3.recommendations[0]["starting_u_value"] == 0.5
        assert recommender3.recommendations[0]["total"] == 7500
        assert recommender3.recommendations[0]["parts"][0]["depth"] == 50

        # With average insulation, no recommendations
        epc_record4 = EPCRecord()
        epc_record4.county = "Greater London"
        epc_record4.floor_level = "0"
        epc_record4.property_type = "House"
        epc_record4.full_sap_epc = {}
        input_property4 = Property(id=1, postcode="F4k3 2", address="223 fake street", epc_record=epc_record4)
        input_property4.floor = {
            'original_description': 'To unheated space, insulated (assumed)',
            'clean_description': 'To unheated space, insulated', 'thermal_transmittance': None,
            'thermal_transmittance_unit': None, 'is_assumed': True, 'is_to_unheated_space': True,
            'is_to_external_air': False, 'is_suspended': False, 'is_solid': False, 'another_property_below': False,
            'insulation_thickness': 'average'
        }
        input_property4.age_band = "C"
        input_property4.set_floor_type()
        input_property4.insulation_floor_area = 100
        input_property4.number_of_floors = 1

        recommender4 = FloorRecommendations(
            property_instance=input_property4,
            materials=materials
        )

        assert not recommender4.recommendations

        recommender4.recommend()

        assert recommender4.estimated_u_value is None

        assert len(recommender4.recommendations) == 0
