import 'package:flutter/services.dart';

class MyRouterHistoryManager {

  //如果页面只需要垂直方向，放入此白名单即可自动处理
  static const onlyVerticalOrientationRouterName = [
    "AUTH_LOGIN", //登录页面，保持垂直布局
    "SPLASH", //闪屏页面，保持垂直布局
  ];

  static final MyRouterHistoryManager _instance = MyRouterHistoryManager._internal();

  factory MyRouterHistoryManager() {
    return _instance;
  }

  MyRouterHistoryManager._internal();

  final List<String?> _routeNames = [];

  // 自己记录路由栈 - 存入
  void putRouterByName(String? routeName) {
    if (routeName != null) {
      _routeNames.add(routeName);
      try2SetVerticalOrientation(routeName);
    }
  }

  // 自己记录路由栈 - 移除
  void removeRouterByName(String? routeName) {
    if (routeName != null && _routeNames.contains(routeName)) {
      _routeNames.remove(routeName);
      try2RestoreOrientation(routeName);
    }
  }

  //尝试设置只竖屏方向展示页面
  void try2SetVerticalOrientation(String routeName) {
    if (onlyVerticalOrientationRouterName.contains(routeName)) {
      //如果包含白名单路由，需要设置垂直
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
      ]);
    }
  }

  //尝试设置横竖屏方向展示页面
  void try2RestoreOrientation(String routeName) {
    if (onlyVerticalOrientationRouterName.contains(routeName)) {
      //如果包含白名单路由，需要恢复全局
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.landscapeLeft,
        DeviceOrientation.landscapeRight,
      ]);
    }
  }

  //获取到全部的RouterName数组
  List<String?> get routeNames => _routeNames;

  //查询当前栈中是否存在指定的路由名称
  bool isRouteExist(String routeName) {
    return _routeNames.contains(routeName);
  }

  // 只是检查栈顶
  bool isTopRouteExist(String routeName) {
    if (_routeNames.isNotEmpty) {
      return _routeNames.last == routeName;
    } else {
      return false;
    }
  }
}
