from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field

from csv_report.csv_report_helper import csv_report_file
from csv_report.csv_report_auto_calculate import CsvReportAutoCalculate

@csv_report_file("xmodem_spend_time")
class XmodemSpendTimeReport(BaseModel, CsvReportAutoCalculate):
    """Device information report model."""
    timestamp: datetime = Field(default_factory=datetime.now)
    cmd_start_timestamp: Optional[datetime] = None
    xmodem_flow_start_timestamp: Optional[datetime] = None
    serial: Optional[str] = None
    ram_file: Optional[str] = None
    ram_size: Optional[int] = None
    init_ms: Optional[int] = None
    upload_ms: Optional[int] = None
    upload_speed_kBps: Optional[float] = None

    def update_before_save(self) -> None:
        if self.ram_size is None:
            self.ram_size = 0
        if self.upload_ms is None:
            self.upload_ms = 0
    
        if self.upload_ms != 0 and self.ram_size != 0:
            self.upload_speed_kBps = self.ram_size / self.upload_ms
        else:
            self.upload_speed_kBps = 0