import 'package:flutter/material.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

enum WidgetType {
  normal, // 正常状态
  skeleton, // 显示骨架
}

/* Widget生成工厂, 用于生成flutter端组件 */
class WidgetFactory {
  static Map<String, WidgetCreater> widgetCreaters = Map();

  /** 
   * @description: 注册组件 
   * @param {name} 组件名，唯一
   * @return: 
   */
  static void regist(String name, WidgetCreater creater) {
    if (!widgetCreaters.containsKey(name)) {
      widgetCreaters[name] = creater;
    }
  }

  /**
   * @description: 创建组件
   * @param {String} 组件注册的名字
   * @return: 
   */
  static List<Widget> create(
    String name, {
    // 组件名
    Map<String, dynamic> model,
    bool isSliver, // 是否加载sliver组件
  }) {
    WidgetCreater creater;
    if (widgetCreaters.containsKey(name)) {
      creater = widgetCreaters[name];
      List<Widget> result = [];
//      if (type == WidgetType.normal)
      result = creater.createWidgets(model);
//      else
//        result = creater.createSkeleton(model);
      if (isSliver) {
        if (creater.isSliverChild()) {
          return result;
        } else {
          return result.map((widget) {
            return SliverToBoxAdapter(child: widget);
          }).toList();
        }
      } else {
        if (creater.isSliverChild()) {
          return _createEmpty(false);
        } else {
          return result;
        }
      }
    } else {
      print('${name} 未注册');
    }
    return _createEmpty(isSliver);
  }

  static List<Widget> _createEmpty(bool isSliver) {
      return isSliver
          ? [
              SliverToBoxAdapter(
                child: Container(height: 0),
              )
            ]
          : [];
  }

  /** 
   * @description: 是否注册组件
   * @param {bool} 
   * @return: 
   */
  static bool hasRegisted(String name) {
    return widgetCreaters.containsKey(name);
  }
}
