import sys, os, re, shutil
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QPushButton, QLabel, QLineEdit,
    QProgressBar, QFileDialog, QVBoxLayout, QWidget, QHBoxLayout
)
from PyQt5.QtCore import Qt, QThread, pyqtSignal

# 백그라운드에서 파일 복사를 수행하는 QThread 클래스
class FileCopyThread(QThread):
    progress = pyqtSignal(int)           # 진행률(%) 업데이트 신호
    copied_count_signal = pyqtSignal(int)  # 복사된 파일 수 업데이트 신호

    def __init__(self, source_dir, target_dir, parent=None):
        super().__init__(parent)
        self.source_dir = source_dir
        self.target_dir = target_dir
        self.is_running = True

    def run(self):
        # 소스 폴더 내의 MOV 파일 목록 (대소문자 구분 없이)
        files = [f for f in os.listdir(self.source_dir) if f.lower().endswith('.mov')]
        total = len(files)
        copied_count = 0

        for i, file_name in enumerate(files):
            if not self.is_running:
                break

            source_file = os.path.join(self.source_dir, file_name)
            # 파일명에서 "TK" 뒤에 숫자가 있는 패턴 추출 (예: TK123)
            match = re.search(r'(TK\d+)', file_name, re.IGNORECASE)
            if match:
                folder_name = match.group(1)
            else:
                folder_name = "Others"  # 패턴이 없으면 "Others" 폴더에 저장

            dest_folder = os.path.join(self.target_dir, folder_name)
            if not os.path.exists(dest_folder):
                os.makedirs(dest_folder)

            dest_file = os.path.join(dest_folder, file_name)
            try:
                shutil.copy2(source_file, dest_file)
                copied_count += 1
            except Exception as e:
                print(f"파일 복사 에러: {source_file} -> {dest_file}\n{e}")

            progress_percent = int((i + 1) / total * 100) if total else 0
            self.progress.emit(progress_percent)
            self.copied_count_signal.emit(copied_count)

    def stop(self):
        self.is_running = False
        self.wait()


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("MOV 파일 복사 앱")
        self.resize(500, 300)

        # 소스 폴더 선택 UI
        self.source_label = QLabel("소스 폴더:")
        self.source_edit = QLineEdit()
        self.source_button = QPushButton("찾아보기")
        self.source_button.clicked.connect(self.select_source)

        # 대상 폴더 선택 UI
        self.target_label = QLabel("대상 폴더:")
        self.target_edit = QLineEdit()
        self.target_button = QPushButton("찾아보기")
        self.target_button.clicked.connect(self.select_target)

        # 복사 시작 및 초기화 버튼
        self.start_button = QPushButton("복사 시작")
        self.start_button.clicked.connect(self.start_copy)
        self.reset_button = QPushButton("초기화")
        self.reset_button.clicked.connect(self.reset)

        # 진행률 표시 및 복사된 파일 수 표시
        self.progress_bar = QProgressBar()
        self.progress_bar.setValue(0)
        self.copied_count_label = QLabel("복사된 파일 수: 0")

        # 레이아웃 구성
        layout = QVBoxLayout()
        source_layout = QHBoxLayout()
        source_layout.addWidget(self.source_label)
        source_layout.addWidget(self.source_edit)
        source_layout.addWidget(self.source_button)
        layout.addLayout(source_layout)

        target_layout = QHBoxLayout()
        target_layout.addWidget(self.target_label)
        target_layout.addWidget(self.target_edit)
        target_layout.addWidget(self.target_button)
        layout.addLayout(target_layout)

        layout.addWidget(self.start_button)
        layout.addWidget(self.reset_button)
        layout.addWidget(self.progress_bar)
        layout.addWidget(self.copied_count_label)

        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

        self.copy_thread = None

    def select_source(self):
        folder = QFileDialog.getExistingDirectory(self, "소스 폴더 선택")
        if folder:
            self.source_edit.setText(folder)

    def select_target(self):
        folder = QFileDialog.getExistingDirectory(self, "대상 폴더 선택")
        if folder:
            self.target_edit.setText(folder)

    def start_copy(self):
        source_dir = self.source_edit.text().strip()
        target_dir = self.target_edit.text().strip()
        if not source_dir or not target_dir:
            return  # 폴더 경로가 없으면 동작하지 않음

        self.start_button.setEnabled(False)
        self.copy_thread = FileCopyThread(source_dir, target_dir)
        self.copy_thread.progress.connect(self.progress_bar.setValue)
        self.copy_thread.copied_count_signal.connect(self.update_copied_count)
        self.copy_thread.finished.connect(self.copy_finished)
        self.copy_thread.start()

    def update_copied_count(self, count):
        self.copied_count_label.setText(f"복사된 파일 수: {count}")

    def copy_finished(self):
        self.start_button.setEnabled(True)

    def reset(self):
        if self.copy_thread is not None:
            self.copy_thread.stop()
            self.copy_thread = None
        self.source_edit.clear()
        self.target_edit.clear()
        self.progress_bar.setValue(0)
        self.copied_count_label.setText("복사된 파일 수: 0")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
