"""
ConfigService - управление настройками приложения
"""
import json
import os
from typing import List, Optional


class ConfigService:
    """Сервис для работы с конфигурацией"""

    SETTINGS_FILE = "astro_settings.json"
    CELESTIAL_BODIES_FILE = "celestial_bodies.json"

    def __init__(self):
        self.config = {
            'cameras': [],
            'lenses': [],
            'telescopes': [],
            'celestial_bodies': [],
            'last_watch_folder': '',
            'last_camera': '',
            'last_lens': ''
        }
        self.load_all()

    def load_all(self):
        """Загружает все настройки"""
        self._load_settings()
        self._load_celestial_bodies()

        # Если список небесных тел пуст - добавляем стандартные
        if not self.config['celestial_bodies']:
            self.config['celestial_bodies'] = [
                "M31 (Andromeda Galaxy)",
                "M42 (Orion Nebula)",
                "M45 (Pleiades)",
                "M57 (Ring Nebula)",
                "Sun",
                "Moon",
                "Jupiter",
                "Saturn"
            ]
            self._save_celestial_bodies()

    def _load_settings(self):
        """Загружает основные настройки (камеры, объективы, телескопы, последнюю папку)"""
        if os.path.exists(self.SETTINGS_FILE):
            try:
                with open(self.SETTINGS_FILE, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self.config['cameras'] = data.get('cameras', [])
                    self.config['lenses'] = data.get('lenses', [])
                    self.config['telescopes'] = data.get('telescopes', [])
                    self.config['last_watch_folder'] = data.get('last_watch_folder', '')
                    self.config['last_camera'] = data.get('last_camera', '')
                    self.config['last_lens'] = data.get('last_lens', '')
            except Exception as e:
                print(f"Ошибка загрузки настроек: {e}")

    def save_settings(self):
        """Сохраняет основные настройки"""
        try:
            with open(self.SETTINGS_FILE, 'w', encoding='utf-8') as f:
                json.dump({
                    'cameras': self.config['cameras'],
                    'lenses': self.config['lenses'],
                    'telescopes': self.config['telescopes'],
                    'last_watch_folder': self.config['last_watch_folder'],
                    'last_camera': self.config['last_camera'],
                    'last_lens': self.config['last_lens']
                }, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"Ошибка сохранения настроек: {e}")

    def _load_celestial_bodies(self):
        """Загружает список небесных тел"""
        if os.path.exists(self.CELESTIAL_BODIES_FILE):
            try:
                with open(self.CELESTIAL_BODIES_FILE, 'r', encoding='utf-8') as f:
                    self.config['celestial_bodies'] = json.load(f)
            except Exception as e:
                print(f"Ошибка загрузки небесных тел: {e}")

    def _save_celestial_bodies(self):
        """Сохраняет список небесных тел"""
        try:
            with open(self.CELESTIAL_BODIES_FILE, 'w', encoding='utf-8') as f:
                json.dump(self.config['celestial_bodies'], f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"Ошибка сохранения небесных тел: {e}")

    # ===== Методы для работы с камерами =====

    def get_cameras(self) -> List[str]:
        return self.config['cameras'].copy()

    def add_camera(self, camera: str):
        if camera and camera not in self.config['cameras']:
            self.config['cameras'].append(camera)
            self.save_settings()

    def remove_camera(self, camera: str):
        if camera in self.config['cameras']:
            self.config['cameras'].remove(camera)
            self.save_settings()

    # ===== Методы для работы с объективами =====

    def get_lenses(self) -> List[str]:
        return self.config['lenses'].copy()

    def add_lens(self, lens: str):
        if lens and lens not in self.config['lenses']:
            self.config['lenses'].append(lens)
            self.save_settings()

    def remove_lens(self, lens: str):
        if lens in self.config['lenses']:
            self.config['lenses'].remove(lens)
            self.save_settings()

    def update_lens(self, old_name: str, new_name: str):
        if old_name in self.config['lenses']:
            idx = self.config['lenses'].index(old_name)
            self.config['lenses'][idx] = new_name
            self.save_settings()

    # ===== Методы для работы с телескопами =====

    def get_telescopes(self) -> List[str]:
        return self.config.get('telescopes', []).copy()

    def add_telescope(self, telescope: str):
        if 'telescopes' not in self.config:
            self.config['telescopes'] = []
        if telescope and telescope not in self.config['telescopes']:
            self.config['telescopes'].append(telescope)
            self.save_settings()

    def remove_telescope(self, telescope: str):
        if 'telescopes' in self.config and telescope in self.config['telescopes']:
            self.config['telescopes'].remove(telescope)
            self.save_settings()

    def update_telescope(self, old_name: str, new_name: str):
        if 'telescopes' in self.config and old_name in self.config['telescopes']:
            idx = self.config['telescopes'].index(old_name)
            self.config['telescopes'][idx] = new_name
            self.save_settings()

    # ===== Методы для работы с небесными телами =====

    def get_celestial_bodies(self) -> List[str]:
        return self.config['celestial_bodies'].copy()

    def add_celestial_body(self, name: str):
        if name and name not in self.config['celestial_bodies']:
            self.config['celestial_bodies'].append(name)
            self._save_celestial_bodies()

    def remove_celestial_body(self, name: str):
        if name in self.config['celestial_bodies']:
            self.config['celestial_bodies'].remove(name)
            self._save_celestial_bodies()

    def update_celestial_body(self, old_name: str, new_name: str):
        if old_name in self.config['celestial_bodies']:
            idx = self.config['celestial_bodies'].index(old_name)
            self.config['celestial_bodies'][idx] = new_name
            self._save_celestial_bodies()

    # ===== Методы для работы с последней папкой и оборудованием =====

    def get_last_watch_folder(self) -> str:
        return self.config.get('last_watch_folder', '')

    def set_last_watch_folder(self, folder: str):
        self.config['last_watch_folder'] = folder
        self.save_settings()

    def get_last_camera(self) -> str:
        return self.config.get('last_camera', '')

    def set_last_camera(self, camera: str):
        self.config['last_camera'] = camera
        self.save_settings()

    def get_last_lens(self) -> str:
        return self.config.get('last_lens', '')

    def set_last_lens(self, lens: str):
        self.config['last_lens'] = lens
        self.save_settings()