import pygame
from solar_model import TICKET_CONFIG


class SolarApp:
    def __init__(self, system, save_callback):
        pygame.init()

        window = TICKET_CONFIG["window"]
        self.width = window["width"]
        self.height = window["height"]
        self.min_width = window["min_width"]
        self.min_height = window["min_height"]

        self.screen = pygame.display.set_mode((self.width, self.height), pygame.RESIZABLE)
        pygame.display.set_caption("Solar System")

        self.clock = pygame.time.Clock()
        self.font = pygame.font.Font(None, 27)
        self.system = system
        self.save_callback = save_callback
        self.running = True
        self.message = ""

    def draw_text(self, text, x, y, color=(30, 30, 30)):
        image = self.font.render(text, True, color)
        self.screen.blit(image, (x, y))

    def draw_panel(self):
        panel = pygame.Surface((330, 205))
        panel.set_alpha(230)
        panel.fill((245, 245, 245))
        self.screen.blit(panel, (15, 15))

        self.draw_text("Билет 3", 30, 30)
        self.draw_text("1 звезда: 11 планет", 30, 62)
        self.draw_text("2 звезда: 12 планет", 30, 94)
        self.draw_text("SPACE — пауза", 30, 126)
        self.draw_text("O — орбиты", 30, 158)
        self.draw_text("S — сохранить", 30, 190)

        if self.system.paused:
            self.draw_text("Пауза", 230, 30, (180, 0, 0))

        if self.message:
            self.draw_text(self.message, 30, 230, (0, 90, 0))

    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False

            if event.type == pygame.VIDEORESIZE:
                self.width = max(self.min_width, event.w)
                self.height = max(self.min_height, event.h)
                self.screen = pygame.display.set_mode((self.width, self.height), pygame.RESIZABLE)
                self.system.resize(self.width, self.height)

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.running = False
                elif event.key == pygame.K_SPACE:
                    self.system.toggle_pause()
                elif event.key == pygame.K_o:
                    self.system.toggle_orbits()
                elif event.key == pygame.K_s:
                    self.save_callback(self.system)
                    self.message = "Состояние сохранено"

    def run(self):
        while self.running:
            self.clock.tick(60)
            self.handle_events()
            self.system.update()

            self.screen.fill((255, 255, 255))
            self.system.draw(self.screen, pygame)
            self.draw_panel()
            pygame.display.update()

        pygame.quit()
