import aframexr
import unittest

from bs4 import BeautifulSoup

from aframexr.api.filters import FilterTransform
from aframexr.utils.constants import AVAILABLE_ENVIRONMENTS, DEFAULT_CHART_DEPTH, DEFAULT_POINT_RADIUS
from aframexr.utils.validators import ERROR_MESSAGES
from tests.constants import *  # Constants used for testing


def _every_radius_does_not_exceed_max_radius(point_chart_html: str, point_chart: aframexr.Chart) -> bool:
    """Verify that every point radius does not exceed the maximum radius."""
    max_radius = point_chart.to_dict()['mark'].get('max_radius', DEFAULT_POINT_RADIUS)

    soup = BeautifulSoup(point_chart_html, 'lxml')
    points = soup.find_all('a-sphere')
    for p in points:
        point_radius = float(p['radius'])  # Radius of the sphere
        if point_radius > max_radius:
            print(f'\nDEBUG: point\'s radius exceed max radius.'
                  f'\n\t- Point\'s radius: {point_radius}'
                  f'\n\t- Max radius: {max_radius}')
            return False
    return True


def _points_are_inside_chart_volume(point_chart_html: str, depth: float = None) -> bool:
    """Verify that no point exceeds the volume dimensions of the chart."""
    soup = BeautifulSoup(point_chart_html, 'lxml')

    chart_depth = DEFAULT_CHART_DEPTH if depth is None else depth
    chart_height = float(soup.select('a-entity[line]')[1]['line'].split(';')[1].split()[2])  # End of the y-axis line
    chart_width = float(soup.select('a-entity[line]')[0]['line'].split(';')[1].split()[1])  # End of the x-axis line

    points = soup.find_all('a-sphere')

    for p in points:
        pos = p['position'].split()
        x, y, z = float(pos[0]), float(pos[1]), float(pos[2])
        radius = float(p.get('radius', '0'))

        # X-axis
        if (x - radius) < 0 or (x + radius) > chart_width:
            print(f'\nDEBUG: point exceed X-axis dimensions.'
                  f'\n\t- Point x-coordinate: {x}'
                  f'\n\t- Point\'s radius: {radius}'
                  f'\n\t- Chart width: {chart_width}')
            return False

        # Y-axis
        if (y - radius) < 0 or (y + radius) > chart_height:
            print(f'\nDEBUG: point exceed Y-axis dimensions.'
                  f'\n\t- Point\'s y-coordinate: {y}'
                  f'\n\t- Point\'s radius: {radius}'
                  f'\n\t- Chart height: {chart_height}')
            return False

        # Z-axis
        if (z + radius) > 0 or (z - radius) < -chart_depth:
            print(f'\nDEBUG: point exceed Z-axis dimensions.'
                  f'\n\t- Point\'s z-coordinate: {z}'
                  f'\n\t- Point\'s radius: {radius}'
                  f'\n\t- Chart depth (negative): {-chart_depth}')
            return False
    return True


class TestMarkPointOK(unittest.TestCase):
    """Mark point OK tests."""

    def test_simple(self):
        """Simple mark point creation."""
        point_chart = aframexr.Chart(DATA).mark_point().encode(x='model', y='sales')
        point_chart_html = point_chart.to_html()
        self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
        self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

    def test_simple_with_pandas_not_installed(self):
        """Simple mark point creation without having pandas installed."""
        import sys
        import importlib
        from unittest import mock

        sys.modules.pop('aframexr', None)
        sys.modules.pop('aframexr.api.components', None)

        with mock.patch.dict(sys.modules, {'pandas': None}):
            import aframexr
            importlib.reload(aframexr)

            point_chart = aframexr.Chart(DATA).mark_point().encode(x='model', y='sales')
            point_chart_html = point_chart.to_html()
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

            import aframexr.api.components as components
            self.assertIsNone(components.pd)
            self.assertIs(components.DataFrame, object)

    def test_from_json(self):
        """Mark point using from_json() method creation."""
        json_string = aframexr.Chart(DATA).mark_point().encode(x='model', y='sales').to_json()
        point_chart = aframexr.Chart.from_json(json_string)
        point_chart_html = point_chart.to_html()
        self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))  # type: ignore
        self.assertTrue(_points_are_inside_chart_volume(point_chart_html))
        self.assertEqual(point_chart.to_json(), json_string)

    def test_data_format(self):
        """Mark point changing data format creation."""
        for d in DATA_FORMATS:
            point_chart = aframexr.Chart(d).mark_point().encode(x='model', y='sales')
            point_chart_html = point_chart.to_html()
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

    def test_position(self):
        """Mark point changing position creation."""
        for p in POSITIONS:
            point_chart = aframexr.Chart(DATA, position=p).mark_point().encode(x='model', y='sales')
            point_chart_html = point_chart.to_html()
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

    def test_position_format(self):
        """Mark point changing position format creation."""
        for p in POSITION_FORMATS:
            point_chart = aframexr.Chart(DATA, position=p).mark_point().encode(x='model', y='sales')
            point_chart_html = point_chart.to_html()
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

    def test_rotation(self):
        """Mark point changing rotation creation."""
        for r in ROTATIONS:
            point_chart = aframexr.Chart(DATA, rotation=r).mark_point().encode(x='model', y='sales')
            point_chart_html = point_chart.to_html()
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

    def test_rotation_format(self):
        """Mark point changing rotation format creation."""
        for r in ROTATION_FORMATS:
            point_chart = aframexr.Chart(DATA, rotation=r).mark_point().encode(x='model', y='sales')
            point_chart_html = point_chart.to_html()
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

    def test_depth(self):
        """Mark point changing depth creation."""
        for d in ALL_MARK_DEPTHS_HEIGHTS_WIDTHS:
            point_chart = aframexr.Chart(DATA, depth=d).mark_point().encode(x='model', y='sales')
            point_chart_html = point_chart.to_html()
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_html, depth=d))

    def test_height(self):
        """Mark point changing height creation."""
        for h in MARK_BAR_POINT_HEIGHTS_WIDTHS:
            point_chart = aframexr.Chart(DATA, height=h).mark_point().encode(x='model', y='sales')
            point_chart_html = point_chart.to_html()
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

    def test_width(self):
        """Mark point changing width creation."""
        for w in MARK_BAR_POINT_HEIGHTS_WIDTHS:
            point_chart = aframexr.Chart(DATA, width=w).mark_point().encode(x='model', y='sales')
            point_chart_html = point_chart.to_html()
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

    def test_size(self):
        """Mark point changing size creation."""
        for s in MARK_BAR_POINT_SIZES:
            point_chart = aframexr.Chart(DATA).mark_point(size=s).encode(x='model', y='sales')
            point_chart_html = point_chart.to_html()
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

    def test_encoding(self):
        """Mark point changing encoding creation."""
        for e in MARK_POINT_ENCODINGS:
            point_chart = aframexr.Chart(DATA).mark_point().encode(**e)
            point_chart_html = point_chart.to_html()
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

    def test_encoding_with_no_Y_axis_displayed(self):
        """Mark point creation with no Y-axis displayed."""
        point_chart = aframexr.Chart(DATA).mark_point().encode(x='model', y=aframexr.Y('sales', axis=None))
        point_chart_html = point_chart.to_html()
        self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))

    def test_filter(self):
        """Mark point changing filter creation."""
        for eq in FILTER_EQUATIONS:
            for f in [eq, FilterTransform.from_equation(eq)]:  # Filter using equation and using FilterTransform object
                point_chart = aframexr.Chart(DATA).mark_point().encode(x='model', y='sales').transform_filter(f)
                point_chart_html = point_chart.to_html()
                self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
                self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

    def test_dynamic_filter(self):
        """Mark point with dynamic filter creation."""
        point_chart_1 = aframexr.Chart(DATA).mark_point().encode(x='motor', y='sales').add_params(DYNAMIC_FILTER)
        point_chart_2 = aframexr.Chart(DATA).mark_point().encode(x='model', y='sales').transform_filter(DYNAMIC_FILTER)
        final_chart = point_chart_1 + point_chart_2
        final_chart.to_html()

    def test_several_filters(self):
        """Mark point with several filters' creation."""
        point_chart = (aframexr.Chart(DATA).mark_point().encode(x='model', y='sales')
                       .transform_filter(SEVERAL_FILTER_EQUATIONS[0]))
        for eq in SEVERAL_FILTER_EQUATIONS[1:]:
            point_chart.transform_filter(eq)

        point_chart_html = point_chart.to_html()
        self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
        self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

    def test_aggregate(self):
        """Mark point changing aggregate creation."""
        for a in AGGREGATES:
            point_chart = (aframexr.Chart(DATA).mark_point().encode(x='model', y='new_field')
                           .transform_aggregate(new_field=f'{a}(sales)'))
            point_chart_html = point_chart.to_html()
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

            point_chart_2 = aframexr.Chart(DATA).mark_point().encode(x='model', y=f'{a}(sales)')
            point_chart_2_html = point_chart_2.to_html()
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_2_html, point_chart_2))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_2_html))

    def test_aggregate_position_rotation_size_height_width_filter(self):
        """Mark point changing position, rotation size, height, width and filter creation."""
        for a, p, r, s, h, w, f in zip(AGGREGATES, POSITIONS, ROTATIONS, MARK_BAR_POINT_SIZES,
                                       MARK_BAR_POINT_HEIGHTS_WIDTHS, MARK_BAR_POINT_HEIGHTS_WIDTHS,
                                       FILTER_EQUATIONS):
            point_chart = (aframexr.Chart(DATA, position=p, rotation=r, height=h, width=w).mark_point(size=s)
                           .encode(x='model', y='agg').transform_filter(f).transform_aggregate(agg=f'{a}(sales)'))
            point_chart_html = point_chart.to_html()
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

    def test_concatenation(self):
        """Mark point concatenation creation."""
        concatenated_chart = (aframexr.Chart(DATA, position=CONCATENATION_POSITIONS[0]).mark_point()
                              .encode(x='model', y='sales'))
        for pos in CONCATENATION_POSITIONS[1:]:
            concatenated_chart += aframexr.Chart(DATA, position=pos).mark_point().encode(x='model', y='sales')

        concatenated_chart_html = concatenated_chart.to_html()
        self.assertTrue(_points_are_inside_chart_volume(concatenated_chart_html))

    def test_environment(self):
        """Scene creation with personalized environment."""
        for e in AVAILABLE_ENVIRONMENTS:
            point_chart = aframexr.Chart(DATA).mark_point().encode(x='model', y='sales')
            point_chart_html = point_chart.to_html(environment=e)
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_html, point_chart))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_html))

    def test_save(self):
        """Mark point saving."""
        import tempfile
        from pathlib import Path

        with tempfile.TemporaryDirectory() as tmpdir:
            temp_html_file_path = Path(tmpdir) / "test.html"
            temp_json_file_path = Path(tmpdir) / "test.json"

            point_chart = aframexr.Chart(DATA).mark_point().encode(x='model', y='sales')
            point_chart.save(str(temp_html_file_path))
            point_chart.save(str(temp_json_file_path))

            self.assertTrue(temp_html_file_path.exists())
            self.assertTrue(temp_json_file_path.exists())

    def test_properties(self):
        """Mark point properties definition."""
        point_chart = aframexr.Chart().mark_point().encode(x='model', y='sales')
        for p, r in zip(POSITIONS, ROTATIONS):
            point_chart_2 = point_chart.properties(data=DATA, position=p, rotation=r)
            point_chart_2_html = point_chart_2.to_html()
            self.assertTrue(_every_radius_does_not_exceed_max_radius(point_chart_2_html, point_chart_2))
            self.assertTrue(_points_are_inside_chart_volume(point_chart_2_html))


class TestMarkPointError(unittest.TestCase):
    """Mark point error tests."""

    def test_load_data_url_error(self):
        """Mark point load data url error."""
        with self.assertRaises(IOError) as error:
            aframexr.Chart(NON_EXISTING_URL_DATA).mark_point().encode(x='model', y='sales').to_html()

        self.assertEqual(str(error.exception), f"Could not load data from URL: {NON_EXISTING_URL_DATA.url}.")

    def test_local_file_does_not_exist(self):
        """Mark point error when local file does not exist."""
        with self.assertRaises(IOError) as error:
            aframexr.Chart(NON_EXISTING_LOCAL_PATH).mark_point().encode(x='model', y='sales').to_html()

        self.assertRegex(str(error.exception), r'Local file .* was not found')

    def test_bad_file_format(self):
        """Mark point error when file format is incorrect."""
        with open(BAD_FILE_FORMAT.url, 'w'):
            pass  # Create a bad format temporal file

        try:
            with self.assertRaises(ValueError) as error:
                aframexr.Chart(BAD_FILE_FORMAT).mark_point().encode(x='model', y='sales').to_html()

            self.assertIn(f'Unsupported file type: ', str(error.exception))
        finally:
            from pathlib import Path
            Path(BAD_FILE_FORMAT.url).unlink()  # Remove the temporal file

    def test_file_is_empty(self):
        """Mark point error when file is empty."""
        with open(EMPTY_FILE.url, 'w'):
            pass  # Create an empty temporal file

        try:
            with self.assertRaises(IOError) as error:
                aframexr.Chart(EMPTY_FILE).mark_point().encode(x='model', y='sales').to_html()

            self.assertIn('Error when processing data. Error: ', str(error.exception))

        finally:
            from pathlib import Path
            Path(EMPTY_FILE.url).unlink()  # Remove the temporal file

    def test_position_error(self):
        """Mark point position error."""
        for p in NOT_3AXIS_POSITIONS_ROTATIONS:
            with self.assertRaises(ValueError) as error:
                aframexr.Chart(DATA, position=p).mark_point().encode(x='model', y='sales').to_html()
            self.assertEqual(str(error.exception), ERROR_MESSAGES['NOT_3_AXES_POSITION_OR_ROTATION'].format(
                pos_or_rot='position', pos_or_rot_value=p
            ))

        for p in NOT_NUMERIC_POSITIONS_ROTATIONS:
            with self.assertRaises(ValueError) as error:
                aframexr.Chart(DATA, position=p).mark_point().encode(x='model', y='sales').to_html()
            self.assertEqual(str(error.exception), 'The position values must be numeric.')

    def test_rotation_error(self):
        """Mark point rotation error."""
        for r in NOT_3AXIS_POSITIONS_ROTATIONS:
            with self.assertRaises(ValueError) as error:
                aframexr.Chart(DATA, rotation=r).mark_point().encode(x='model', y='sales').to_html()
            self.assertEqual(str(error.exception), ERROR_MESSAGES['NOT_3_AXES_POSITION_OR_ROTATION'].format(
                pos_or_rot='rotation', pos_or_rot_value=r
            ))

        for r in NOT_NUMERIC_POSITIONS_ROTATIONS:
            with self.assertRaises(ValueError) as error:
                aframexr.Chart(DATA, rotation=r).mark_point().encode(x='model', y='sales').to_html()
            self.assertEqual(str(error.exception), 'The rotation values must be numeric.')

    def test_size_error(self):
        """Mark point size error."""
        for s in NOT_GREATER_THAN_0_NUMBERS:
            with self.assertRaises(ValueError) as error:
                aframexr.Chart(DATA).mark_point(size=s).encode(x='model', y='sales')
            self.assertEqual(str(error.exception), ERROR_MESSAGES['POSITIVE_NUMBER'].format(param_name='size'))

    def test_depth_error(self):
        """Mark point error when depth is incorrect."""
        for d in NOT_GREATER_THAN_0_NUMBERS:
            with self.assertRaises(ValueError) as error:
                aframexr.Chart(DATA, depth=d).mark_point().encode(x='model', y='sales').to_html()
            self.assertEqual(
                str(error.exception),
                ERROR_MESSAGES['POSITIVE_NUMBER'].format(param_name='depth')
            )

    def test_height_error(self):
        """Mark point height error."""
        for h in NOT_GREATER_THAN_0_NUMBERS:
            with self.assertRaises(ValueError) as error:
                aframexr.Chart(DATA, height=h).mark_point().encode(x='model', y='sales').to_html()
            self.assertEqual(str(error.exception), ERROR_MESSAGES['POSITIVE_NUMBER'].format(param_name='height'))

    def test_width_error(self):
        """Mark point width error."""
        for w in NOT_GREATER_THAN_0_NUMBERS:
            with self.assertRaises(ValueError) as error:
                aframexr.Chart(DATA, width=w).mark_point().encode(x='model', y='sales').to_html()
            self.assertEqual(str(error.exception), ERROR_MESSAGES['POSITIVE_NUMBER'].format(param_name='width'))

    def test_encoding_error(self):
        """Mark point encoding error."""
        for e in NON_EXISTING_MARK_BAR_POINT_ENCODINGS:
            with self.assertRaises(KeyError) as error:
                point_chart = aframexr.Chart(DATA).mark_point().encode(**e)
                point_chart.to_html()
            self.assertIn('Data has no field ', str(error.exception))

        for e in NOT_VALID_MARK_BAR_POINT_ENCODINGS:
            with self.assertRaises(ValueError) as error:
                aframexr.Chart(DATA).mark_point().encode(**e).to_html()
            self.assertEqual(str(error.exception), ERROR_MESSAGES['LESS_THAN_2_XYZ_ENCODING'])

    def test_encoding_error_invalid_encoding_type(self):
        """Mark point encoding error with invalid encoding type."""
        with self.assertRaises(ValueError) as error:
            bad_encoding_type = 'BAD_ENCODING'
            aframexr.Chart(DATA).mark_point().encode(x=f'model:{bad_encoding_type}', y='sales').to_html()
        self.assertEqual(str(error.exception), ERROR_MESSAGES['ENCODING_TYPE'].format(encoding_type=bad_encoding_type))

    def test_encoding_error_not_encoded(self):
        """Mark point encoding error. Encoding not in specifications."""
        with self.assertRaises(ValueError) as error:
            point_chart = aframexr.Chart(DATA).mark_point()
            point_chart.to_html()
        self.assertEqual(str(error.exception), ERROR_MESSAGES['ENCODING_NOT_IN_SPECS'])

    def test_filter_warning(self):
        """Mark point filter warning."""
        for f in WARNING_FILTER_EQUATIONS:
            with self.assertWarns(UserWarning) as warning:
                filt_chart = aframexr.Chart(DATA).mark_point().encode(x='model', y='sales').transform_filter(f)
                filt_chart.to_html()
            self.assertEqual(
                str(warning.warning),
                f'Data does not contain values for the filter: {FilterTransform.from_equation(f).to_dict()}'
            )

    def test_filter_error(self):
        """Mark point filter error."""
        for f in SYNTAX_ERROR_FILTER_EQUATIONS:
            with self.assertRaises(SyntaxError) as error:
                filt_chart = aframexr.Chart(DATA).mark_point().encode(x='model', y='sales').transform_filter(f)
                filt_chart.to_html()
            self.assertEqual(str(error.exception), 'Incorrect syntax, must be datum.{field} {operator} {value}')

    def test_aggregate_error(self):
        """Mark point aggregate error."""
        for a in NOT_VALID_AGGREGATES:
            with self.assertRaises(ValueError) as error:
                agg_chart = (aframexr.Chart(DATA).mark_point().encode(x='model', y='sales')
                             .transform_aggregate(new_field=f'{a}(sales)'))
                agg_chart.to_html()
            self.assertEqual(str(error.exception), ERROR_MESSAGES['AGGREGATE_OPERATION'].format(operation=a))

    def test_aggregate_error_not_defined_encoding_channels(self):
        """Mark point aggregate error raised when encoding channels are not defined in aggregation."""
        with self.assertRaises(ValueError) as error:
            agg_chart = (aframexr.Chart(DATA).mark_point().encode(x='model', y='sales')
                         .transform_aggregate(mean_sales='mean(sales)', groupby=['model']))
            agg_chart.to_html()

        self.assertRegex(str(error.exception), r'Encoding channel\(s\) .* must be defined in aggregate .*'
                                               r', otherwise that fields will disappear.')

    def test_environment_error(self):
        """Scene creation with invalid personalized environment."""
        environment = 'bad_environment'
        point_chart = aframexr.Chart(DATA).mark_point().encode(x='model', y='sales')
        with self.assertRaises(ValueError) as error:
            # noinspection PyTypeChecker
            point_chart.to_html(environment=environment)
        self.assertEqual(str(error.exception), ERROR_MESSAGES['ENVIRONMENT'].format(environment=environment))
