from __future__ import annotations

from datetime import date
from http import HTTPStatus
from urllib.parse import parse_qs


class RotationRoutesMixin:
    def _handle_rotation_get(self, parsed) -> bool:
        if parsed.path == "/api/rotation/history":
            query = parse_qs(parsed.query)
            trade_date = query.get("trade_date", [date.today().isoformat()])[0]
            try:
                self.send_json(self.application_service.rotation_history(trade_date, 9))
            except (TypeError, ValueError) as exc:
                self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
            return True
        if parsed.path == "/api/rotation/members":
            query = parse_qs(parsed.query)
            try:
                self.send_json(
                    self.application_service.rotation_sector_members(
                        query.get("trade_date", [date.today().isoformat()])[0],
                        query.get("sector", [""])[0],
                    )
                )
            except (TypeError, ValueError) as exc:
                self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
            return True
        return False
