#!/usr/bin/perl

use strict;
use warnings;

use File::Slurp ();
use Text::CSV;

use lib 'libs';
use API::VehicleAdmin;

my @CSV_FIELDS_REQUIRED = qw(
    year
    make
    model
    subModel
    bodyCode
    bodyType
    engine
);

my @ALLOWED_MAKES = (
    'Mercedes Benz',
    'Porsche',
);

main();
exit 0;

###############################################################################

sub main {
    logInfo( "Starting" );

    my $filePath = $ARGV[0]
        or die "vehicle data filePath required";

    my $csv = File::Slurp::read_file( $filePath );

    my $vehicleInputs = parseCSV( $csv );
    logInfo( "Vehicles parsed (" . scalar( @{ $vehicleInputs } ) . ")" );

    validateVehicleInputs( $vehicleInputs );
    logInfo( "Vehicles validated" );

    if ( not @{ $vehicleInputs } ) {
        logInfo( "No Vehicles to import" );
        return;
    }

    for my $vehicleInput ( @{ $vehicleInputs } ) {
        my $vehicleConfigID = importVehicle( $vehicleInput );
        logInfo( "Created vehicleConfigID ${vehicleConfigID}" );
    }

    logInfo( "Done" );
    return;
}

###############################################################################

sub logInfo {
    my ( $msg ) = @_;
    print localtime() . " ${msg}\n";
    return;
}

###############################################################################

sub parseCSV {
    my ( $data ) = @_;

    open( my $fh, "<", \$data );

    my $csv = Text::CSV->new();
    my $headers = $csv->getline( $fh )
        or die "unable to read header line";

    die "no headers detected" unless @{ $headers };

    $csv->column_names( @{ $headers } );

    my $rates = $csv->getline_hr_all( $fh );

    return $rates;
}

###############################################################################

sub validateVehicleInputs {
    my ( $vehicleInputs ) = @_;

    for my $vehicleInput ( @{ $vehicleInputs } ) {
        for my $field ( @CSV_FIELDS_REQUIRED ) {
            if ( not defined( $vehicleInput->{ $field } ) ) {
                die "missing ${field}";
            }
            if ( length( $vehicleInput->{ $field } ) == 0 ) {
                die "no value in ${field}";
            }
        }
        my $makeAllowed = grep { $_ eq $vehicleInput->{'make'} } @ALLOWED_MAKES;
        if ( not $makeAllowed ) {
            die "make not allowed: ".$vehicleInput->{'make'};
        }
    }

    return;
}

###############################################################################

sub importVehicle {
    my ( $vehicleInput ) = @_;

    my $vehicleAdmin = API::VehicleAdmin->new({
        'input' => $vehicleInput,
    });

    my $vehicleConfigID = $vehicleAdmin->_createVehicleConfig({
        'steps' => [ @CSV_FIELDS_REQUIRED ],
        'detailVehicle' => 1,
    });

    return $vehicleConfigID;
}
