/////////////////////////////////////////////////////////////////////////////////////////
//  file   : chat.c
//  author : Alain Greiner
//  date   : november 2020
/////////////////////////////////////////////////////////////////////////////////////////
// This file describes a single thread, fifo based, chat application.
//
// The chat[0] process is supposed to communicate with another chat[1] process through
// two fifos, identified by the P0P1_FIFO_PATH & P1P0_fifo_PATH arguments.
//
// The behaviour depends on the process argument (argc/argv mechanism) :
// - when this argument is 0 the process is P0 (write P0P1 fifo / read P1P0 fifo).
// - when this argument is non-zero, the process is P1 (write P1P0 fifo / read P0P1 fifo).
//
// - For a P0 process :
//    1) it creates the P0P1 fifo.
//    2) it open a write-only file descriptor on this P0P1 fifo.
//    3) in a waiting loop it open a read-only file descriptor on the P1P0 fifo.
//    4) it enters the chat loop, starting by a send().
//
// - For a P1 process :
//    1) it creates the P1P0 fifo.
//    2) it open a write-only file descriptor on this P1P0 fifo.
//    3) in a waiting loop, it open a read-only file descriptor on the P0P1 fifo.
//    4) it enters the chat loop, starting by a receive().
//    
// Both sides can stop the communication and exit by sending an "exit" string.
///////////////////////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <almosmkh.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>


#define P0P1_FIFO_PATH  "/misc/chat_p0p1_fifo" 
#define P1P0_FIFO_PATH  "/misc/chat_p1p0_fifo" 

#define CHAT_BUF_SIZE       256

#define DEBUG_MAIN          0

///////////////////////////////////////////////////////////////////
// - This function send the string captured on STDIN to the fifo
//   and return the number of characters sent if success.
// - It send an empty string (first character == 0),
//   and return 0 when the captured string is "exit".
///////////////////////////////////////////////////////////////////
int chat_send( int is_0,
               int fdid )
{
    char   buffer[CHAT_BUF_SIZE];   // string buffer for one message
    int    size;                    // string length (including NUL)
    int    nbytes;                  // number of characters actually sent 

    // display local prompt
    printf("\n[local] " );

    // build local message
    size = get_string( buffer , CHAT_BUF_SIZE );

    // send local message
    nbytes = write( fdid , buffer , size );

    if( nbytes != size )
    {
        printf("\n[chat P%d error] cannot send\n", is_0 );
        // return exit
        return 0;
    }

    // handle "exit" string
    if( strncmp( "exit" , buffer , 4 ) == 0 ) 
    {
        printf("\n[chat P%d] local message is <exit> => quit\n", is_0 );
        // return exit
        return 0;
    }

    // return success
    return nbytes;
 
}  // end chat_send()

///////////////////////////////////////////////////////////////////////
// - This function copies the string received from the fifo to STDOUT,
//   and return the number of characters received if success.
// - It returns 0 when the received string is empty, too long,
//   or when an EOF signals end of communication.
///////////////////////////////////////////////////////////////////////
int chat_receive( int is_0,
                  int fdid )
{
    char   buffer[CHAT_BUF_SIZE];      // string buffer for one message
    int    nbytes;                     // number of characters received in one read

    // initialize loop variables
    int    space    = CHAT_BUF_SIZE;   // number of empty slots in buffer
    int    received = 0;               // total number of received bytes
    char * buf      = &buffer[0];

    // display remote prompt
    printf("\n[remote] ");

    // get remote message
    while( 1 )
    {
        // try to read as many bytes as available space in buffer
        nbytes = read( fdid , buf , space );

        // analyse number of bytes received
        if( (nbytes < 0) || ((nbytes + received) >= CHAT_BUF_SIZE) )  // error
        {
            printf("\n\n[chat P%d error] received %d bytes\n", is_0 , received + nbytes );
            // return exit
            return 0;
        }
        else if( buffer[nbytes - 1] != 0 )    // uncompleted string => new read
        {
            buf      = buf + nbytes;
            space    = space + nbytes;
            received = received + nbytes;
        }
        else                                  // NUL terminated string => exit loop
        {
            received = received + nbytes;
            break;
        }
    }
     
    // display remote message
    printf("%s\n", buffer );

    // handle "exit" string 
    if( strncmp( "exit" , buffer , 4 ) == 0 ) // handle "exit" string
    {
        printf("\n[chat P%d] remote message is <exit> => quit \n", is_0 );
        // return exit
        return 0;
    }

    // return success
    return received;

}  // end chat_receive()



///////////////////////////////////
int main( int argc , char ** argv )
{
    int                  error;
    int                  is_0;             // P0 process when zero / P1 process otherwise
    int                  read_fdid;        // file descriptor index for read fifo
    int                  write_fdid;       // file descriptor index for read fifo
    unsigned long long   start_cycle;

    // check arguments
    if( argc == 0 )
    {
        printf("\n[chat error] cannot get process argument / pid %x\n", getpid() );
        exit( 1 );
    }

    // get process index 0/1
    is_0 = (strcmp( "0" , argv[0] ) == 0);

    // get  start cycle
    get_cycle( &start_cycle );

    //////////////////////////
    if( is_0 )   // P0 process
    {
        printf("\n[chat P0] starts at cycle %d\n", (unsigned int)start_cycle );

        // 1. P0 creates the P0P1 fifo
        error = mkfifo( P0P1_FIFO_PATH, 0 );

        if( error )
        {
            printf("\n[chat P0 error] cannot create P0P1 fifo\n" );
            exit( 1 );
        }

        printf("\n[chat P0] P0P1 fifo created\n");

        // 2. P0 open the read_fdid file descriptor
        write_fdid = open( P0P1_FIFO_PATH,
                           O_WRONLY, 0 ); 

        if( write_fdid < 0 )
        {
            printf("\n[chat P0 error] cannot get write_fdid for P0P1 fifo\n" );
            exit( 1 );
        }

        printf("\n[chat P0] got write_fdid = %d\n", write_fdid );

        // 3. P0 try to open the read_fdid file descriptor
        while( 1 )
        {
            read_fdid = open( P1P0_FIFO_PATH,
                              O_RDONLY, 0 );

            if( read_fdid > 0 ) break;

            pthread_yield();
        }

        printf("\n[chat P0] got read_fdid = %d\n", read_fdid );

#if DEBUG_MAIN
display_fd_array( getpid() );
#endif
        // 4. P0 enter the chat loop
        while( 1 )
        {
            // handle received remote message
            if( chat_send( is_0, write_fdid ) == 0 ) break;

            // handle local send message
            if( chat_receive( is_0, read_fdid ) == 0 ) break;
        }

        // 5. P0 closes file descriptors
        close( write_fdid );
        close( read_fdid );

        printf("\n[chat P0] closed write_fdid & read_fdid\n");

        // 6. P0 deletes fifo
        unlink( P0P1_FIFO_PATH );

        printf("\n[chat P0] deleted P0P1 fifo\n");
    }
    /////////////////////////
    else        // P1 process
    {
        printf("\n[chat P1] starts at cycle %d\n", (unsigned int)start_cycle );

        // 1. P1 creates the P1P0 fifo
        error = mkfifo( P1P0_FIFO_PATH, 0 );

        if( error )
        {
            printf("\n[chat P1 error] cannot create P1P0 fifo\n");
            exit( 1 );
        }

        printf("\n[chat P1] P1P0 fifo created\n");

        // 2. P1 open the read_fdid file descriptor
        write_fdid = open( P1P0_FIFO_PATH,
                           O_WRONLY, 0 ); 

        if( write_fdid < 0 )
        {
            printf("\n[chat P1 error] cannot get write_fdid for P1P0 fifo\n" );
            exit( 1 );
        }

        printf("\n[chat P1] got write_fdid = %d\n", write_fdid );

        // 3. P1 try to open the read_fdid file descriptor
        while( 1 )
        {
            read_fdid = open( P0P1_FIFO_PATH,
                              O_RDONLY, 0 );

            if( read_fdid > 0 ) break;
        }

        printf("\n[chat P1] got read_fdid = %d\n", read_fdid );

#if DEBUG_MAIN
display_fd_array( getpid() );
#endif

        // 4. P1 enter the chat loop 
        while( 1 )
        {
            // handle received remote message
            if( chat_receive( is_0, read_fdid ) == 0 ) break;

            // handle local send message
            if( chat_send( is_0, write_fdid ) == 0 ) break;
        }

        // 5. P1 closes file descriptors
        close( write_fdid );
        close( read_fdid );

        printf("\n[chat P1] closed write_fdid & read_fdid\n");

        // 6. P1 deletes fifo
        unlink( P1P0_FIFO_PATH );

        printf("\n[chat P1] deleted P1P0 fifo\n");
    }

    exit( 0 );

    return 0;

}  // end main()
