# ENG-LAPTOP-0002A: display profile bootstrap.
# Must run before the Qt app is created.
import os
import socket


def armor_display_profile():
    forced = os.environ.get(
        "ARMOR_DISPLAY_PROFILE",
        "",
    ).strip().lower()

    if forced in ["pi", "laptop"]:
        return forced

    host = socket.gethostname()
    arch = (
        os.uname().machine
        if hasattr(os, "uname")
        else ""
    )

    if host == "armor-core":
        return "pi"

    if arch == "x86_64":
        return "laptop"

    return "pi"


ARMOR_DISPLAY_PROFILE = armor_display_profile()

if ARMOR_DISPLAY_PROFILE == "laptop":
    os.environ.setdefault(
        "QT_AUTO_SCREEN_SCALE_FACTOR",
        "0",
    )
    os.environ.setdefault(
        "QT_SCALE_FACTOR",
        "1.35",
    )


import sys

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
    QApplication,
    QStackedWidget,
    QVBoxLayout,
    QWidget,
)

from core.version import get_window_title

from modules.dashboard import Dashboard
from modules.laptop_dashboard import LaptopDashboard
from modules.shire import ShirePage
from modules.forge import ForgePage
from modules.archive import ArchivePage
from modules.atlas import AtlasPage
from modules.media import MediaPage
from modules.system import SystemPage
from modules.sentinel import SentinelPage
from modules.education import EducationPage
from modules.agents import AgentsPage
from modules.tasks import TasksPage
from modules.settings import SettingsPage
from modules.global_prompt_bar import GlobalPromptBar


class ArmorStationStack(QStackedWidget):
    """ARMOR station navigation stack."""

    def __init__(self, parent=None):
        super().__init__(parent)

        self.swipe_start_x = None
        self.swipe_start_y = None

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Right:
            self.next_station()

        elif event.key() == Qt.Key_Left:
            self.previous_station()

        elif event.key() == Qt.Key_Home:
            self.setCurrentIndex(0)

        else:
            super().keyPressEvent(event)

    def mousePressEvent(self, event):
        self.swipe_start_x = event.pos().x()
        self.swipe_start_y = event.pos().y()

        super().mousePressEvent(event)

    def mouseReleaseEvent(self, event):
        if self.swipe_start_x is not None:
            dx = (
                event.pos().x()
                - self.swipe_start_x
            )

            dy = (
                event.pos().y()
                - self.swipe_start_y
            )

            if (
                abs(dx) > 90
                and abs(dx) > abs(dy)
            ):
                if dx < 0:
                    self.next_station()
                else:
                    self.previous_station()

        self.swipe_start_x = None
        self.swipe_start_y = None

        super().mouseReleaseEvent(event)

    def next_station(self):
        next_index = self.currentIndex() + 1

        if next_index >= self.count():
            next_index = 0

        self.setCurrentIndex(next_index)

    def previous_station(self):
        previous_index = self.currentIndex() - 1

        if previous_index < 0:
            previous_index = self.count() - 1

        self.setCurrentIndex(previous_index)


class ArmorOS(QWidget):
    """ARMOR window with a persistent laptop prompt bar."""

    def __init__(self):
        super().__init__()

        self.setWindowTitle(
            get_window_title()
        )

        if ARMOR_DISPLAY_PROFILE == "laptop":
            self.setWindowTitle(
                "ARMOR OS - Laptop Command Station"
            )

            self.setWindowFlag(
                Qt.FramelessWindowHint,
                True,
            )

        self.stack = ArmorStationStack(self)

        if ARMOR_DISPLAY_PROFILE == "laptop":
            home_page = LaptopDashboard(
                self.stack
            )
        else:
            home_page = Dashboard(
                self.stack
            )

        self.shire_page = ShirePage(
            self.stack
        )

        pages = [
            home_page,
            self.shire_page,
            ForgePage(self.stack),
            ArchivePage(self.stack),
            AtlasPage(self.stack),
            MediaPage(self.stack),
            SystemPage(self.stack),
            AgentsPage(self.stack),
            TasksPage(self.stack),
            SettingsPage(self.stack),
            SentinelPage(self.stack),
            EducationPage(self.stack),
        ]

        for page in pages:
            self.stack.addWidget(page)

        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

        self.prompt_bar = None

        if ARMOR_DISPLAY_PROFILE == "laptop":
            self.prompt_bar = GlobalPromptBar(
                self.stack,
                self.shire_page,
                self,
            )

            layout.addWidget(
                self.prompt_bar
            )

        layout.addWidget(
            self.stack,
            1,
        )


def main():
    app = QApplication(sys.argv)

    app.setStyleSheet("""
        QMainWindow, QWidget, QStackedWidget {
            background-color: #000000;
            color: #e8fff2;
        }
    """)

    window = ArmorOS()
    window.showFullScreen()

    return app.exec_()


if __name__ == "__main__":
    raise SystemExit(main())
