# VisionBuilder.UI.Statistics

A .NET 8 library for collecting and managing image processing statistics in VisionBuilder applications. This library tracks session data, defect counts, and exports statistics to CSV files for analysis.

## Overview

The VisionBuilder.UI.Statistics library provides comprehensive statistics collection for computer vision and image processing workflows. It automatically tracks session events, image processing results, and defect data, organizing them into structured CSV reports.

## Features

- **Session Tracking**: Monitors recognition sessions from start to end
- **Defect Recording**: Tracks image processing errors and defect types
- **CSV Export**: Generates detailed statistics files for analysis
- **Configurable Paths**: Flexible output directory configuration with variable substitution
- **Monthly Reports**: Aggregates data into monthly statistics files
- **Thread-Safe**: Uses concurrent collections for reliable multi-threaded operation

## Core Components

### VisionBuilderStatistics

The main statistics collection class that implements `IInitializable`.

**Key Responsibilities:**
- Monitors recognition control events
- Records session start/end times
- Tracks defects and error types
- Exports data to CSV files

**Event Handlers:**
- `SessionStarted`: Initializes new statistics session
- `ImageProcessed`: Records defect data for failed images
- `SessionEnded`: Finalizes and exports session statistics

### VisionBuilderStatisticsSettings

Configuration class for statistics collection settings.

**Properties:**
- `CameraName`: Identifier for the camera/station
- `PathTemplate`: Configurable output directory with variable substitution

**Supported Variables:**
- `$RECIPE_NAME` - Current recipe name
- `$DEFECT_NAME` - Defect type name
- `$CAMERA_NAME` - Camera identifier
- Time variables: `$HOUR`, `$MINUTE`, `$SECOND`, `$MS`
- Date variables: `$DAY`, `$MONTH`, `$YEAR`
- Session start variables: `$SS_HOUR`, `$SS_MINUTE`, `$SS_SECOND`, `$SS_DAY`, `$SS_MONTH`, `$SS_YEAR`

## Output Files

### statistics_by_events.csv
Contains detailed event-by-event statistics with columns:
- Start Date, Start Time
- End Date, End Time
- Error Time
- Product (Recipe)
- Error (Defect Type)

### statistics_month.csv
Monthly aggregated statistics for trend analysis.

## Dependencies

- **Serilog** (4.3.0): Logging framework
- **Inspectron.Statistics**: Core statistics functionality
- **VisionBuilder.UI.Common**: Common UI components and interfaces

## Usage

```csharp
// Configure settings
var settings = new VisionBuilderStatisticsSettings("Camera1")
{
    PathTemplate = @"..\Data\Statistics\$SS_MONTH $SS_YEAR\$RECIPE_NAME\"
};

// Initialize statistics collector
var statistics = new VisionBuilderStatistics(
    settings, 
    recognitionControl, 
    loadingService
);

// Initialize to process any pending statistics
statistics.Initialize();
```

## Architecture

The library follows an event-driven architecture:

1. **Session Start**: Creates temporary CSV file and begins tracking
2. **Image Processing**: Records defects as they occur during processing
3. **Session End**: Finalizes temporary file and merges into main statistics
4. **Cleanup**: Removes temporary files and updates monthly aggregations

## File Management

- Temporary files use GUID naming: `tmp_{guid}.csv`
- Files are sorted by creation time during consolidation
- Automatic directory creation for output paths
- Safe cleanup of temporary files after processing

## Error Handling

- Comprehensive exception handling with Serilog logging
- Graceful handling of invalid date/time data
- Safe file operations with proper resource disposal
- Loading service integration for user feedback

## Thread Safety

Uses `ConcurrentDictionary<string, int>` for defect counting to ensure thread-safe operations in multi-threaded image processing environments.

## Target Framework

- .NET 8.0
- Nullable reference types enabled
- Implicit usings enabled