import 'package:fis_lib_report/report/cellPostion.dart';
import 'package:fis_lib_report/report/element.dart';
import 'package:fis_lib_report/report/element_type.dart';
import 'package:fis_lib_report/report/interfaces/cell.dart';
import 'package:fis_lib_report/report/interfaces/element.dart';
import 'package:fis_lib_report/report/interfaces/grid.dart';
import 'package:fis_lib_report/report/interfaces/position_layout.dart';
import 'package:fis_lib_report/report/interfaces/report_element.dart';
import 'package:fis_lib_report/report/rt_Cell.dart';

class RTGrid extends Element implements IGrid {
  @override
  List<RTColumnDefinition>? columnDefinitions = [];

  @override
  List<IElement>? elements = [];

  @override
  List<RTRowDefinition>? rowDefinitions = [];

  bool? isDelete;

  bool? isInsertColumn;

  int? deleteRowIndex;

  int? deleteColumnIndex;

  double? divideWidth;

  bool? isMergeCell;

  int? mergeDeleteStartColumnIndex;

  int? mergeDeleteEndColumnIndex;

  Map<CellPostion, ICell>? cells = {};

  RTGrid(IReportElement parent) : super.fromParent(parent) {
    horizontalAlignment = HorizontalLayout.Left;
    elementType = ElementType.rtGrid;
    columnDefinitions = [];
    rowDefinitions = [];
    cells = {};
  }

  RTGrid.fromJson(Map<String, dynamic> json) : super.fromJson(json) {
    horizontalAlignment = HorizontalLayout.Left;

    List<dynamic> jsonColumnDefinitions = json["ColumnDefinitions"] ?? [];
    jsonColumnDefinitions.forEach((map) {
      if (map is Map<String, dynamic>) {
        final rtcolumn = RTColumnDefinition.fromJson(map);
        columnDefinitions!.add(rtcolumn);
      }
    });
    isDelete = json['IsDelete'];
    isInsertColumn = json['IsInsertColumn'];
    deleteRowIndex = json['DeleteRowIndex'];
    deleteColumnIndex = json['DeleteColumnIndex'];
    divideWidth = json['DivideWidth'];
    isMergeCell = json['IsMergeCell'];
    mergeDeleteStartColumnIndex = json['MergeDeleteStartColumnIndex'];
    mergeDeleteEndColumnIndex = json['MergeDeleteEndColumnIndex'];
    List<dynamic> jsonRowDefinitions = json['RowDefinitions'] ?? [];
    jsonRowDefinitions.forEach((map) {
      if (map is Map<String, dynamic>) {
        final rtRow = RTRowDefinition.fromJson(map);
        rowDefinitions!.add(rtRow);
      }
    });

    //TODO(Loki): elements init
    List<dynamic> jsonCells = json['Cells'];
    int index = 0;
    CellPostion key = new CellPostion();
    jsonCells.forEach((map) {
      if (index.isEven) {
        key = CellPostion.fromJson(map);
        cells![key] = new ICell();
      } else {
        final jsonType = map['ElementType'];
        final type = ElementType.fromJson(jsonType);
        if (type.name == ElementType.rtCell!.name) {
          final cell = RTCell.fromJson(map);
          cells![key] = cell;
        }
      }
      index++;
    });
  }
}