from __future__ import annotations
from PyQt6.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit,
    QPushButton, QFileDialog, QFormLayout,
)
from core.config import Config

class SetupDialog(QDialog):
    def __init__(self, config: Config, parent=None):
        super().__init__(parent)
        self.setWindowTitle("my-publisher — Setup")
        self.setMinimumWidth(500)
        self._config = config
        self._build_ui()

    def _build_ui(self):
        layout = QVBoxLayout(self)
        layout.addWidget(QLabel("Configura my-publisher prima di iniziare."))

        form = QFormLayout()

        self._blog_repo = QLineEdit(self._config.blog_repo)
        browse_btn = QPushButton("Sfoglia...")
        browse_btn.clicked.connect(self._browse_repo)
        row = QHBoxLayout()
        row.addWidget(self._blog_repo)
        row.addWidget(browse_btn)
        form.addRow("Blog repo:", row)

        self._transart = QLineEdit(self._config.transart_script)
        form.addRow("transart.py:", self._transart)

        self._typora = QLineEdit(self._config.typora_bin)
        form.addRow("Typora bin:", self._typora)

        self._typora_args = QLineEdit(self._config.typora_args)
        form.addRow("Typora args:", self._typora_args)

        layout.addLayout(form)

        btns = QHBoxLayout()
        save_btn = QPushButton("Salva")
        save_btn.clicked.connect(self._save)
        btns.addStretch()
        btns.addWidget(save_btn)
        layout.addLayout(btns)

    def _browse_repo(self):
        path = QFileDialog.getExistingDirectory(self, "Seleziona blog repo")
        if path:
            self._blog_repo.setText(path)

    def _save(self):
        self._config.blog_repo = self._blog_repo.text().strip()
        self._config.transart_script = self._transart.text().strip()
        self._config.typora_bin = self._typora.text().strip()
        self._config.typora_args = self._typora_args.text().strip()
        self._config.save()
        self.accept()
