# Cherrypy-foundation
# Copyright (C) 2026 IKUS Software
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
import importlib
import os
from unittest import skipIf, skipUnless

import cherrypy
from cherrypy.test import helper

import cherrypy_foundation.tools.jinja2  # noqa
from cherrypy_foundation.components import StaticMiddleware
from cherrypy_foundation.tests import SeleniumUnitTest
from cherrypy_foundation.url import url_for

HAS_JINJAX = importlib.util.find_spec("jinjax") is not None

VENDOR_TEST = os.environ.get('VENDOR_TEST', None)

env = cherrypy.tools.jinja2.create_env(
    package_name=__package__,
)


class Static:

    components = StaticMiddleware()


@cherrypy.tools.sessions()
@cherrypy.tools.jinja2(on=False, env=env)
class Root:

    static = Static()

    @cherrypy.expose
    @cherrypy.tools.jinja2(template='test_chart.html')
    def index(self, **kwargs):
        return {}


@skipUnless(HAS_JINJAX, reason='Required jinjax')
@skipIf(VENDOR_TEST == '0', reason='Chart test disabled')
class ChartTest(SeleniumUnitTest, helper.CPWebCase):
    interactive = False

    @classmethod
    def setup_server(cls):
        cherrypy.tree.mount(Root(), '/')

    def test_get_page(self):
        # Given a page with chart
        self.getPage(url_for('/'))
        self.assertStatus(200)
        # Then page is render using chart
        self.assertInBody('<canvas ')

    def test_get_page_selenium(self):
        # Given  page with chart
        with self.selenium() as driver:
            # When querying the page
            driver.get(url_for('/'))
            # Then page load without error
            self.assertFalse(driver.get_log('browser'))
            # Then page contains our chart
            chart = driver.find_element('css selector', 'canvas.cf-chart-js')
            self.assertTrue(chart)
            # Then our canvas has a size ratio of 3
            self.assertAlmostEqual(chart.size['height'], 413, delta=10)
            self.assertAlmostEqual(chart.size['width'], 1264, delta=10)


if __name__ == '__main__':
    cherrypy.quickstart(Root())
