import 'package:liftmanager/common/common.dart';

import '../entity_factory.dart';

class BaseEntity<T> {
  int statusCode;
  String message;
  T data;
  List<T> listData = [];

  BaseEntity(this.statusCode, this.message, this.data);

  BaseEntity.fromJson(Map<String, dynamic> jsons, Function buildFun) {
    var json = jsons["data"];
    if (json == null) return;

    statusCode = int.parse(json[Constant.code]);
    message = json[Constant.message];
    if (json.containsKey(Constant.data)) {
      if (json[Constant.data] is List) {
        (json[Constant.data] as List).forEach((item) {
//          listData.add(_generateOBJ<T>(item));
          if (buildFun != null) {
            listData.add(buildFun(item));
          } else {
            listData.add(_generateOBJ<T>(item));
          }
        });
      } else {
        if (json[Constant.data] != null) {
//          data = _generateOBJ<T>(json[Constant.data]);
          if (buildFun != null) {
            data = buildFun(json[Constant.data]);
          } else {
            data = _generateOBJ<T>(json[Constant.data]);
          }
        }
      }
    }
  }

  S _generateOBJ<S>(json) {
    if (S.toString() == "String") {
      return json.toString() as S;
    }
    if (S.toString() == "bool") {
      return json as S;
    }
    if (S.toString() == "int") {
      return json as S;
    }
    if (S.toString() == "double") {
      return json as S;
    } else if (T.toString() == "Map<dynamic, dynamic>") {
      return json as S;
    } else {
//      print(json);
      return EntityFactory.generateOBJ(json);
    }
  }
}
