package GLPI::Agent::Task::Inventory::Win32::USB;

use strict;
use warnings;

use parent 'GLPI::Agent::Task::Inventory::Module';

use GLPI::Agent::Tools;
use GLPI::Agent::Tools::Win32;
use GLPI::Agent::Tools::USB;

use constant    category    => "usb";

sub isEnabled {
    return 1;
}

sub doInventory {
    my (%params) = @_;

    my $inventory = $params{inventory};

    foreach my $device (_getDevices(logger => $params{logger}, datadir => $params{datadir})) {
        $inventory->addEntry(
            section => 'USBDEVICES',
            entry   => $device
        );
    }
}

sub _getDevices {
    my (%params) = @_;

    my @devices;
    my $seen;

    foreach my $device (_getDevicesFromWMI(%params)) {

        next if $device->skip();

        # Avoid duplicates
        my $dedupkey = join('-', $device->vendorid, $device->productid, $device->serial);
        next if $seen->{$dedupkey}++;

        # cleanup pseudo serial generated by windows
        $device->delete_serial() if $device->serial =~ /&/;

        # Update device
        $device->update_by_ids();
        $device->update();

        push @devices, $device->dump();
    }

    return @devices;
}

sub _getDevicesFromWMI {
    my (%params) = @_;

    my @devices;

    my ($vendorid, $productid, $serial);

    foreach my $object (getWMIObjects(
        class      => 'CIM_LogicalDevice',
        properties => [ qw/Caption DeviceID Name/ ]
    )) {
        next unless ($vendorid, $productid, $serial) = $object->{DeviceID} =~ /^USB\\VID_(\w+)&PID_(\w+)\\(.*)/;

        # Support manufacturers wrongly using iSerial with fields definition
        $serial = $1 if $serial =~ /^S\/N:([0-9A-F]+)/i;

        push @devices, GLPI::Agent::Tools::USB->new(
            logger      => $params{logger},
            caption     => $object->{Caption},
            name        => $object->{Name},
            vendorid    => $vendorid,
            productid   => $productid,
            serial      => $serial
        );
    }

    return @devices;
}

1;
