# Copyright 2026 Espressif Systems (Shanghai) Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os

from PySide6.QtWidgets import (QDialog, QFileDialog, QHBoxLayout, QLabel,
                               QListWidget, QMessageBox, QPushButton,
                               QVBoxLayout)


class Launcher(QDialog):
    def __init__(self, profile_dir):
        super().__init__()
        self.profile_dir = profile_dir
        self.selected_profile_path = None
        self.profile_map = {}  # label -> full_path
        self.setWindowTitle("Select Profile")
        self.resize(500, 400)
        self._init_ui()
        self._load_profiles()

    def _init_ui(self):
        layout = QVBoxLayout(self)

        layout.addWidget(QLabel("Available Profiles:"))

        self.list_widget = QListWidget()
        self.list_widget.itemDoubleClicked.connect(self._on_open)
        layout.addWidget(self.list_widget)

        btn_layout = QHBoxLayout()
        btn_browse = QPushButton("Browse...")
        btn_browse.clicked.connect(self._on_browse)

        btn_open = QPushButton("Open")
        btn_open.clicked.connect(self._on_open)
        btn_cancel = QPushButton("Cancel")
        btn_cancel.clicked.connect(self.reject)

        btn_layout.addWidget(btn_browse)
        btn_layout.addStretch()
        btn_layout.addWidget(btn_open)
        btn_layout.addWidget(btn_cancel)

        layout.addLayout(btn_layout)

    def _load_profiles(self):
        if self.profile_dir and os.path.exists(self.profile_dir):
            for root, _, files in os.walk(self.profile_dir):
                for f in files:
                    if f.endswith(".json"):
                        full_path = os.path.join(root, f)
                        # Create a nice label based on relative path or internal name
                        rel_path = os.path.relpath(full_path, self.profile_dir)
                        self._add_profile_item(rel_path, full_path)

    def _add_profile_item(self, label, full_path):
        if label not in self.profile_map:
            self.list_widget.addItem(label)
            self.profile_map[label] = full_path

    def _on_browse(self):
        files, _ = QFileDialog.getOpenFileNames(
            self, "Import Profiles", "", "JSON Profiles (*.json)"
        )
        if files:
            for f in files:
                label = os.path.basename(f)
                # If name exists, append partial path or just unique ID?
                # For now, just allow them to show up.
                self._add_profile_item(f"{label} ({os.path.dirname(f)})", f)

    def _on_open(self):
        item = self.list_widget.currentItem()
        if not item:
            return

        label = item.text()
        self.selected_profile_path = self.profile_map.get(label)
        if self.selected_profile_path:
            self.accept()
