#!perl -w
use strict;
use warnings;

use threads;
use threads::shared;
use Thread::Queue;

use Win32::GUI;
use ThreadSafe;

sub CW_USEDEFAULT() {0x80000000};

sub WM_APP()    {32768};
sub WM_PIPE0()  {WM_APP+10};
sub WM_PIPE1()  {WM_PIPE0+1};
sub WM_PIPE2()  {WM_PIPE0+2};

sub M_END()     {0};
sub M_START()   {1};
sub M_DATA()    {2};


my $win = new Win32::GUI::Window(
            -name       => 'win',
            -caption    => 'ThreadSafe 1',
            -size       => [300,400],
            -pos        => [CW_USEDEFAULT,CW_USEDEFAULT],
            );
            
$win->AddButton(
			-name		=> 'btn',
			-text		=> 'Send Data',
			
);

ThreadSafe::Port($win, \&Main_Callback);
ThreadSafe::Anchor(WM_PIPE0,0);

my $pipe1 = threads->new(sub { Pipe(1) });
my $pipe2 = threads->new(sub { Pipe(2) });

$win->Show();
Win32::GUI::Dialog();
print "Waiting for thread join()\n";
$pipe1->join();
$pipe2->join();

sub win_Terminate{
	#Send Kill Messages to threads
    ThreadSafe::SendMessage(WM_PIPE1,M_END,0);
    ThreadSafe::SendMessage(WM_PIPE2,M_END,0);
    #Cleanup.
    ThreadSafe::Close();
    return -1;
}

sub btn_Click{
	ThreadSafe::SendMessage(WM_PIPE1, M_DATA, 0, qw(dum di dum));
	ThreadSafe::SendMessage(WM_PIPE0, M_DATA, 0, qw(dum di dum));
	return 1;
}

#@
sub Main_Callback{
	my ( $obj, $wparam, $lparam, $type, $msgcode, @data ) = @_;
	
	print "Main Callback :",join(',',@data),"\n";
	
	return 1;
}

#@ PIPEX Threads
sub Pipe{
    my $id = shift;
    print "Pipe $id : Starting\n";
    print "Pipe $id : Anchoring\n";
    ThreadSafe::Anchor(WM_PIPE0 + $id, 0);
    print "Pipe $id : Entering Dialog\n";
    my $result = ThreadSafe::Dialog(sub { Pipe_Callback($id, @_) });
    print "Pipe $id : Exited Dialog ($result)\n";
    ThreadSafe::Anchor(WM_PIPE0 + $id, 1);
    print "Pipe $id : De-Anchored\n";
    return $result;
}

sub Pipe_Callback{
    my ( $id, $handle, $wparam, $lparam, $type, $msgcode, @data ) = @_;
    if( $wparam == M_END && $msgcode == WM_PIPE0 + $id){
        print "Pipe $id : Signal to end Dialog\n";
        return -1;
    }else{
        print "Pipe $id : Got ( $handle, $wparam, $lparam, (".join(',',@data ).") )\n";
        if( $wparam == M_DATA){
        	ThreadSafe::SendMessage(WM_PIPE0, M_DATA, 0, qw(la di da));
        }
    }
    
    return 1;
}