

import 'dart:convert';
import 'package:uuid/uuid.dart';

import 'product.dart';

class CartLineItem {
  int? id;
  double? unitPrice;
  double? totalPrice;
  Product? product;
  String? name;
  String? description;
  double? quantity;
  String? uuid;
  String? parentUuid;

  CartLineItem() {
    uuid = Uuid().v4();
  }

  CartLineItem.fromJson(Map<String, dynamic> json)
    : id = json['id'],
      unitPrice = double.parse(json['unit_price'].toString()),
      totalPrice = json['total_price'] != null ? double.parse(json['total_price'].toString()) : double.parse(json['unit_price'].toString()) * double.parse(json['quantity'].toString()),
      product = json['product'] != null ? Product.fromJson(json['product']) : null,
      name = json['name'],
      description = json['description'],
      quantity = double.parse(json['quantity'].toString()),
      uuid = Uuid().v4();

  Map<String, dynamic> toJson() => {
    'id': id,
    'unit_price': unitPrice,
    'total_price': totalPrice,
    'product': product,
    'name': name,
    'description': description,
    'quantity': quantity,
    'uuid': uuid,
    'parentUuid': parentUuid
  };

  @override
  String toString() {
    return json.encode(this);
  }

  double getTotalPrice() {
    totalPrice = (unitPrice ?? 0.0) * (quantity ?? 0);
    return totalPrice ?? 0.0;
  }
}