"""
Тесты для страницы Кубсат
"""
from django.test import TestCase, Client
from django.contrib.auth.models import User
from django.urls import reverse

from mainapp.models import Source, ObjItem, Parameter, Satellite, Polarization, Modulation, ObjectInfo
from mainapp.forms import KubsatFilterForm


class KubsatViewTest(TestCase):
    """Тесты для представления KubsatView"""
    
    def setUp(self):
        """Подготовка тестовых данных"""
        self.client = Client()
        self.user = User.objects.create_user(
            username='testuser',
            password='testpass123',
            first_name='Test',
            last_name='User'
        )
        self.client.login(username='testuser', password='testpass123')
        
        # Создаем тестовые данные
        self.satellite = Satellite.objects.create(name='Test Sat', norad=12345)
        self.polarization = Polarization.objects.create(name='H')
        self.modulation = Modulation.objects.create(name='QPSK')
        self.object_info = ObjectInfo.objects.create(name='Test Type')
        
        self.source = Source.objects.create(info=self.object_info)
        self.objitem = ObjItem.objects.create(name='Test Object', source=self.source)
        self.parameter = Parameter.objects.create(
            objitem=self.objitem,
            id_satellite=self.satellite,
            frequency=11000.0,
            freq_range=36.0,
            polarization=self.polarization,
            modulation=self.modulation
        )
    
    def test_kubsat_page_accessible(self):
        """Проверка доступности страницы Кубсат"""
        response = self.client.get(reverse('mainapp:kubsat'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'mainapp/kubsat.html')
    
    def test_kubsat_page_requires_login(self):
        """Проверка что страница требует авторизации"""
        self.client.logout()
        response = self.client.get(reverse('mainapp:kubsat'))
        self.assertEqual(response.status_code, 302)  # Redirect to login
    
    def test_kubsat_filter_form(self):
        """Проверка работы формы фильтров"""
        form = KubsatFilterForm()
        self.assertIn('satellites', form.fields)
        self.assertIn('polarization', form.fields)
        self.assertIn('frequency_min', form.fields)
        self.assertIn('modulation', form.fields)
    
    def test_kubsat_filter_by_satellite(self):
        """Проверка фильтрации по спутнику"""
        response = self.client.get(
            reverse('mainapp:kubsat'),
            {'satellites': [self.satellite.id]}
        )
        self.assertEqual(response.status_code, 200)
        self.assertIn('sources', response.context)
    
    def test_kubsat_export_view_accessible(self):
        """Проверка доступности экспорта"""
        response = self.client.post(
            reverse('mainapp:kubsat_export'),
            {'source_ids': [self.source.id]}
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            response['Content-Type'],
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
    
    def test_kubsat_export_filename(self):
        """Проверка имени экспортируемого файла"""
        response = self.client.post(
            reverse('mainapp:kubsat_export'),
            {'source_ids': [self.source.id]}
        )
        self.assertIn('attachment', response['Content-Disposition'])
        self.assertIn('kubsat_', response['Content-Disposition'])
        self.assertIn('.xlsx', response['Content-Disposition'])


class KubsatFilterFormTest(TestCase):
    """Тесты для формы KubsatFilterForm"""
    
    def test_form_fields_exist(self):
        """Проверка наличия всех полей формы"""
        form = KubsatFilterForm()
        expected_fields = [
            'satellites', 'band', 'polarization', 'frequency_min', 'frequency_max',
            'freq_range_min', 'freq_range_max', 'modulation', 'object_type',
            'object_ownership', 'objitem_count', 'has_plans', 'success_1',
            'success_2', 'date_from', 'date_to'
        ]
        for field in expected_fields:
            self.assertIn(field, form.fields)
    
    def test_form_valid_data(self):
        """Проверка валидации формы с корректными данными"""
        form_data = {
            'frequency_min': 10000.0,
            'frequency_max': 12000.0,
            'objitem_count': '1'
        }
        form = KubsatFilterForm(data=form_data)
        self.assertTrue(form.is_valid())
    
    def test_form_optional_fields(self):
        """Проверка что все поля необязательные"""
        form = KubsatFilterForm(data={})
        self.assertTrue(form.is_valid())
