from tkinter import Tk, Label, Button, Entry, filedialog, messagebox, Listbox, simpledialog, OptionMenu, StringVar
import os
from gtts import gTTS
from moviepy.editor import concatenate_videoclips, AudioFileClip, ImageClip, CompositeVideoClip, TextClip
import tempfile
from datetime import datetime

class VideoProject:
    def __init__(self):
        self.texts = []
        self.images = []
        self.background_music = None
        self.video_type = "참교육"

    def add_text(self, text):
        self.texts.append(text)

    def add_image(self, image_path):
        self.images.append(image_path)

    def set_background_music(self, music_path):
        self.background_music = music_path

    def set_video_type(self, video_type):
        self.video_type = video_type

class VideoMakerApp:
    def __init__(self, master):
        self.master = master
        master.title("유튜브 쇼츠 제작기")

        self.project = VideoProject()

        self.label = Label(master, text="유튜브 쇼츠 제작기에 오신 것을 환영합니다!")
        self.label.pack()

        self.text_entry = Entry(master)
        self.text_entry.pack()

        self.add_text_button = Button(master, text="텍스트 추가", command=self.add_text)
        self.add_text_button.pack()

        self.add_image_button = Button(master, text="이미지 추가", command=self.add_image)
        self.add_image_button.pack()

        self.add_music_button = Button(master, text="배경음 추가", command=self.add_background_music)
        self.add_music_button.pack()

        self.type_var = StringVar(master)
        self.type_var.set("참교육")
        self.type_dropdown = OptionMenu(master, self.type_var, "참교육", "야썰", "어이없음", "감동", command=self.project.set_video_type)
        self.type_dropdown.pack()

        self.create_video_button = Button(master, text="동영상 만들기", command=self.create_video_with_speech)
        self.create_video_button.pack()

        self.item_listbox = Listbox(master)
        self.item_listbox.pack()

    def add_text(self):
        text = self.text_entry.get()
        if text:
            self.project.add_text(text)
            self.item_listbox.insert('end', f"텍스트: {text}")
            messagebox.showinfo("성공", "텍스트가 추가되었습니다.")

    def add_image(self):
        file_path = filedialog.askopenfilename()
        if file_path:
            self.project.add_image(file_path)
            self.item_listbox.insert('end', f"이미지: {os.path.basename(file_path)}")
            messagebox.showinfo("성공", "이미지가 추가되었습니다.")

    def add_background_music(self):
        file_path = filedialog.askopenfilename()
        if file_path:
            self.project.set_background_music(file_path)
            messagebox.showinfo("성공", "배경음이 설정되었습니다.")

    def create_video_with_speech(self):
        clips = []
        for text, image_path in zip(self.project.texts, self.project.images):
            tts = gTTS(text=text, lang='ko')
            temp_file = tempfile.NamedTemporaryFile(delete=False)
            tts.save(temp_file.name)
            temp_file.close()

            audio_clip = AudioFileClip(temp_file.name)
            image_clip = ImageClip(image_path).set_duration(audio_clip.duration).set_fps(24)
            text_clip = TextClip(text, fontsize=24, color='white').set_position('bottom').set_duration(audio_clip.duration)
            composite_clip = CompositeVideoClip([image_clip, text_clip]).set_duration(audio_clip.duration).set_fps(24).set_audio(audio_clip)
            clips.append(composite_clip)

            os.unlink(temp_file.name)

        final_clip = concatenate_videoclips(clips)

        if self.project.background_music:
            background_audio = AudioFileClip(self.project.background_music).set_duration(final_clip.duration).set_fps(24)
            final_clip = final_clip.set_audio(background_audio)

        result_dir = "Result"
        if not os.path.exists(result_dir):
            os.makedirs(result_dir)
        today = datetime.now().strftime("%Y%m%d")
        file_name = f"{today}_{self.project.video_type}.mp4"
        final_path = os.path.join(result_dir, file_name)

        final_clip.write_videofile(final_path, fps=24)

        messagebox.showinfo("완료", "동영상이 성공적으로 생성되었습니다.")

root = Tk()
my_gui = VideoMakerApp(root)
root.mainloop()