# -*- coding: utf-8 -*-

# -----------------------------------------------------------------------------
# Copyright (c) 2016-2024 Anaconda, Inc.
#
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
# -----------------------------------------------------------------------------

"""Survey dialog implementation."""

from __future__ import annotations

import typing

from qtpy.QtCore import Signal, QUrl
from qtpy.QtWebEngineWidgets import QWebEngineView, QWebEnginePage, QWebEngineSettings
from qtpy.QtWidgets import QDialog
from qtpy.QtWidgets import QVBoxLayout, QWidget, QHBoxLayout

from anaconda_navigator.config import CONF
from anaconda_navigator.config import feature_flags
from anaconda_navigator.widgets.dialogs import FrameBase, ButtonDialogClose
from .common import ExtendedWebEnginePage

if typing.TYPE_CHECKING:
    import typing_extensions


class SurveyDialog(QDialog):
    """Web-based survey dialog."""

    sig_finished = Signal()

    def __init__(self, parent: QWidget | None = None):
        """Initialize new :class:`~CloudTab` instance."""
        super().__init__(parent=parent)

        self.__view: 'typing_extensions.Final[QWebEngineView]' = QWebEngineView()
        self.__view.setPage(ExtendedWebEnginePage(self, origin='survey'))

        self.button_close_dialog = ButtonDialogClose(self)
        self.button_close_dialog.clicked.connect(self.sig_finished)

        title_layout: typing.Final[QHBoxLayout] = QHBoxLayout()
        title_layout.addStretch(1)
        title_layout.addWidget(self.button_close_dialog)

        self.frame_title_bar: typing.Final[FrameBase] = FrameBase(self)
        self.frame_title_bar.setLayout(title_layout)

        layout: 'typing_extensions.Final[QVBoxLayout]' = QVBoxLayout()
        layout.addWidget(self.frame_title_bar)
        layout.addWidget(self.view)

        self.setLayout(layout)

        self.view.load(QUrl(feature_flags.FEATURE_FLAGS.survey_url))
        self.view.loadFinished.connect(self.__process_view_load)

        self.page.settings().setAttribute(QWebEngineSettings.ShowScrollBars, False)

    @property
    def view(self) -> 'QWebEngineView':
        """Current page instance."""
        return self.__view

    @property
    def page(self) -> 'QWebEnginePage':
        """Current page instance."""
        return self.view.page()

    def __process_view_load(self, status: bool) -> None:
        """Close dialog if view load failed."""
        self.view.loadFinished.disconnect()
        if status:
            CONF.set('internal', 'passed_survey_url', feature_flags.FEATURE_FLAGS.survey_url)
            return

        self.sig_finished.emit()
        self.close()
