import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
import vlc
import pygame
import random
import os
import sys
from datetime import datetime, time
import json

class RadioPlayer:
    def __init__(self, master):
        self.master = master
        master.title("Интернет-радио плеер")
        master.geometry("500x600")

        self.style = ttk.Style()
        self.style.theme_use('clam')

        self.stations = self.load_stations()

        pygame.init()
        pygame.mixer.init()

        self.ad_interval = 30 * 60 * 1000
        self.is_playing = False

        self.vlc_instance = vlc.Instance()
        self.player = self.vlc_instance.media_player_new()

        self.volume = 100  # Громкость по умолчанию
        self.ad_volume = 20  # Громкость рекламы

        self.create_widgets()
        self.load_settings()
        self.update_status()

    def create_widgets(self):
        main_frame = ttk.Frame(self.master, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)

        ttk.Label(main_frame, text="Выберите радиостанцию:").pack()
        self.station_var = tk.StringVar()
        self.station_combo = ttk.Combobox(main_frame, textvariable=self.station_var, values=list(self.stations.keys()))
        self.station_combo.pack()
        self.station_combo.bind("<<ComboboxSelected>>", self.update_url)

        ttk.Button(main_frame, text="Редактировать станции", command=self.edit_stations).pack()

        ttk.Label(main_frame, text="URL радиостанции:").pack()
        self.url_input = ttk.Entry(main_frame, width=50)
        self.url_input.pack()

        self.play_button = ttk.Button(main_frame, text="Воспроизвести", command=self.play_radio)
        self.play_button.pack()
        self.pause_button = ttk.Button(main_frame, text="Пауза", command=self.pause_radio)
        self.pause_button.pack()
        self.stop_button = ttk.Button(main_frame, text="Остановить", command=self.stop_radio)
        self.stop_button.pack()

        ttk.Label(main_frame, text="Интервал рекламы (минуты):").pack()
        self.ad_interval_input = ttk.Entry(main_frame)
        self.ad_interval_input.pack()
        self.ad_interval_input.insert(0, str(self.ad_interval // 60000))
        ttk.Button(main_frame, text="Обновить интервал", command=self.update_ad_interval).pack()

        ttk.Label(main_frame, text="Громкость (0-100):").pack()
        self.volume_slider = ttk.Scale(main_frame, from_=0, to=100, orient=tk.HORIZONTAL, command=self.set_volume)
        self.volume_slider.set(self.volume)
        self.volume_slider.pack()

        self.restart_button = ttk.Button(main_frame, text="Перезапустить", command=self.restart_app)
        self.restart_button.pack()
        self.close_button = ttk.Button(main_frame, text="Закрыть", command=self.master.quit)
        self.close_button.pack()

        self.status_var = tk.StringVar()
        ttk.Label(main_frame, textvariable=self.status_var).pack()

    def update_url(self, event):
        selected_station = self.station_var.get()
        self.url_input.delete(0, tk.END)
        self.url_input.insert(0, self.stations[selected_station])

    def play_radio(self):
        url = self.url_input.get()
        try:
            media = self.vlc_instance.media_new(url)
            self.player.set_media(media)
            self.player.audio_set_volume(self.volume)
            self.player.play()
            self.is_playing = True
            self.schedule_ad()
            self.check_closing_time()
            self.save_settings()
            self.update_status()
        except Exception as e:
            messagebox.showerror("Ошибка", f"Не удалось загрузить или воспроизвести URL: {e}")

    def pause_radio(self):
        if self.is_playing:
            self.player.pause()
            self.is_playing = not self.player.is_playing()
            self.update_status()

    def stop_radio(self):
        self.player.stop()
        self.is_playing = False
        self.update_status()

    def play_ad(self):
        if self.is_playing:
            ad_files = self.find_audio_files("ad")
            if ad_files:
                ad_file = random.choice(ad_files)
                self.player.audio_set_volume(self.ad_volume)
                pygame.mixer.Sound(ad_file).play()
                self.master.after(5000, lambda: self.player.audio_set_volume(self.volume))
            self.schedule_ad()

    def schedule_ad(self):
        self.master.after(self.ad_interval, self.play_ad)

    def check_closing_time(self):
        if self.is_playing:
            now = datetime.now()
            current_time = now.time()
            current_day = now.weekday()

            closing_time = time(19, 0) if current_day < 5 else time(18, 0)
            time_to_close = (datetime.combine(now.date(), closing_time) - now).total_seconds()

            if 0 < time_to_close <= 1800:
                if time_to_close <= 600:
                    closing_file = self.find_audio_files("close_10_min")
                elif time_to_close <= 1200:
                    closing_file = self.find_audio_files("close_20_min")
                else:
                    closing_file = self.find_audio_files("close_30_min")

                if closing_file:
                    pygame.mixer.Sound(closing_file[0]).play()

            self.master.after(60000, self.check_closing_time)

    def update_ad_interval(self):
        try:
            new_interval = int(self.ad_interval_input.get()) * 60 * 1000
            self.ad_interval = new_interval
            messagebox.showinfo("Успех", "Интервал рекламы обновлен")
            self.save_settings()
        except ValueError:
            messagebox.showerror("Ошибка", "Пожалуйста, введите корректное число минут")

    def set_volume(self, value):
        self.volume = int(value)
        self.player.audio_set_volume(self.volume)
        self.save_settings()

    def restart_app(self):
        self.master.destroy()
        os.execl(sys.executable, sys.executable, *sys.argv)

    def save_settings(self):
        settings = {
            "last_url": self.url_input.get(),
            "ad_interval": self.ad_interval,
            "volume": self.volume
        }
        with open("settings.json", "w") as f:
            json.dump(settings, f)

    def load_settings(self):
        try:
            with open("settings.json", "r") as f:
                settings = json.load(f)
            self.url_input.insert(0, settings.get("last_url", ""))
            self.ad_interval = settings.get("ad_interval", 30 * 60 * 1000)
            self.ad_interval_input.delete(0, tk.END)
            self.ad_interval_input.insert(0, str(self.ad_interval // 60000))
            self.volume = settings.get("volume", 100)
            self.volume_slider.set(self.volume)
        except FileNotFoundError:
            pass

    def update_status(self):
        status = "Воспроизводится" if self.is_playing else "Остановлено"
        self.status_var.set(f"Статус: {status}")

    def find_audio_files(self, prefix):
        return [f for f in os.listdir() if f.startswith(prefix) and f.endswith(".mp3")]

    def edit_stations(self):
        edit_window = tk.Toplevel(self.master)
        edit_window.title("Редактировать станции")

        for name, url in self.stations.items():
            frame = ttk.Frame(edit_window)
            frame.pack(fill=tk.X, padx=5, pady=2)

            ttk.Label(frame, text=name, width=20).pack(side=tk.LEFT)
            url_entry = ttk.Entry(frame, width=40)
            url_entry.pack(side=tk.LEFT, padx=5)
            url_entry.insert(0, url)
            ttk.Button(frame, text="Удалить", command=lambda n=name: self.delete_station(n, edit_window)).pack(side=tk.LEFT)

        ttk.Button(edit_window, text="Добавить станцию", command=lambda: self.add_station(edit_window)).pack(pady=10)
        ttk.Button(edit_window, text="Сохранить", command=lambda: self.save_stations(edit_window)).pack(pady=5)

    def delete_station(self, name, window):
        del self.stations[name]
        self.refresh_edit_window(window)

    def add_station(self, window):
        name = simpledialog.askstring("Добавить станцию", "Введите название станции:")
        if name:
            url = simpledialog.askstring("Добавить станцию", "Введите URL станции:")
            if url:
                self.stations[name] = url
                self.refresh_edit_window(window)

    def save_stations(self, window):
        for widget in window.winfo_children():
            if isinstance(widget, ttk.Frame):
                name = widget.winfo_children()[0].cget("text")
                url = widget.winfo_children()[1].get()
                self.stations[name] = url

        self.save_stations_to_file()
        self.station_combo['values'] = list(self.stations.keys())
        window.destroy()

    def refresh_edit_window(self, window):
        for widget in window.winfo_children():
            widget.destroy()
            self.edit_stations()

            def save_stations_to_file(self):
                    with open("stations.json", "w") as f:
                        json.dump(self.stations, f)

            def load_stations(self):
                    try:
                        with open("stations.json", "r") as f:
                            return json.load(f)
                    except FileNotFoundError:
                        return {
                            "Радио 1": "https://retro.hostingradio.ru:8014/retro320.mp3",
                            "Радио 2": "https://nashe1.hostingradio.ru/nashe-128.mp3",
                            "Радио 3": "http://ep128.hostingradio.ru:8030/ep128"
                        }

if __name__ == '__main__':
                root = tk.Tk()
                player = RadioPlayer(root)
                root.mainloop()