#!/usr/bin/perl -w

use Test::More 'no_plan';
use Test::Differences;

use File::Path;

use_ok 'XS::Writer';

my $writer = XS::Writer->new(
    package   => 'Some::Employee',
    include   => <<'END',
#include "employee.h"
END

);
isa_ok $writer, 'XS::Writer';
is $writer->package,    "Some::Employee";
is $writer->xs_type,    "Some__Employee";
is $writer->xs_prefix,  "Some__Employee_";
is $writer->xs_file,    "lib/Some/Employee_struct.xsi";
is $writer->header_file,"Employee_struct.h";

$writer->struct(<<'END');
    typedef struct employee {
        char *      name;    /* this is a comment */
        double      salary;  /* this is another comment */
        int         id;
        // and this is a comment
    };
END

$writer->xs_file( "t/test/". $writer->xs_file );
$writer->header_file( "t/test/". $writer->header_file );

my $xs = <<"END";
# Generated by XS::Writer $XS::Writer::VERSION

#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

#include "t/test/Employee_struct.h"

MODULE = Some::Employee  PACKAGE = Some::Employee  PREFIX = Some__Employee_

Some::Employee
Some__Employee_new( char* CLASS )
    CODE:
       RETVAL = ((malloc(sizeof(employee))));
        if( RETVAL == NULL ) {
           warn( "unable to create new Some::Employee" );
       }
    OUTPUT:
       RETVAL


void
Some__Employee_free( Some::Employee self )
    CODE:
        free(self);


int
Some__Employee_id( Some::Employee self, ... )
    CODE:
        if( items > 1 )
            self->id = SvIV(ST(1));
        RETVAL = self->id;
    OUTPUT:
        RETVAL


char *
Some__Employee_name( Some::Employee self, ... )
    CODE:
        if( items > 1 )
            self->name = SvPV_nolen(ST(1));
        RETVAL = self->name;
    OUTPUT:
        RETVAL


double
Some__Employee_salary( Some::Employee self, ... )
    CODE:
        if( items > 1 )
            self->salary = SvNV(ST(1));
        RETVAL = self->salary;
    OUTPUT:
        RETVAL


END

eq_or_diff $writer->make_xs, $xs;

$writer->write_xs;
END { rmtree "t/test" }

ok open my $fh, $writer->xs_file
    or diag "Can't open @{[ $writer->xs_file ]}: $!";
eq_or_diff join("", <$fh>), $xs;

ok open $fh, $writer->header_file
    or diag "Can't open @{[ $writer->heder_file ]}: $!";
eq_or_diff join("", <$fh>), <<"END";
/* Generated by XS::Writer $XS::Writer::VERSION */

#include "employee.h"


typedef employee *     Some__Employee;
END



{
    my $struct = XS::Writer->new(
        package     => 'Something'
    );
    
    $struct->struct(<<'END');
        struct foo {
            char    *thing;
        };
END

    is_deeply $struct->struct_elements, { thing => "char *" },
        "can parse 'char *foo' style";
}


# Tests for packages with more than one set of ::
{
    my $writer = XS::Writer->new(
        package     => 'Foo::Bar::Baz::Bim'
    );
    
    is $writer->xs_file, 'lib/Foo/Bar/Baz/Bim_struct.xsi';
    is $writer->xs_type, 'Foo__Bar__Baz__Bim';
}
