/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*-  */
/*
 * socketcom.cc
 * Copyright (C) 2014 Unknown <root@on6jc>
 *
 * socket_test is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * socket_test is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <glib.h>

#include "fifocom.h"

GIOChannel *channel;
char *client_fn, *server_fn;

gboolean
read_watch(GIOChannel *source, GIOCondition cond, gpointer data)
{
  char bff[100];
  GError  *error = NULL;
  gsize   bytes_read;
  GIOStatus ret;
  
  printf("read_watch called\n");
  ret = g_io_channel_read_chars(source, bff, sizeof(bff), &bytes_read, &error);
  
  if (ret == G_IO_STATUS_ERROR)
    g_error("Error reading: %s\n", error->message);
  else {
    bff[bytes_read] = 0;
    ((read_callback) data)(bff);
    printf("Got: %s\n", bff);
  }
  return TRUE;
}

gboolean
write_chars(GIOChannel *dest, char *message)
{
  int out_fd;
    
  printf("Trying to write %s\n", message);
  
  out_fd = open(client_fn, O_WRONLY);
  write(out_fd, message, strlen(message));
  close(out_fd);
  
  return TRUE;
}

void
start_comm(const char *fifo_root, read_callback callback)
{ 
  int in_fd, ch_id;
  
  server_fn = g_strdup_printf("%s.server", fifo_root);
  client_fn = g_strdup_printf("%s.client", fifo_root);
  
  if (g_file_test(server_fn, G_FILE_TEST_EXISTS))
    unlink(server_fn);				// g_remove wasn't declared???
    
  // Then create a new one
  mkfifo(server_fn, 0666);
  
  // Open the file for reading
  in_fd = open(server_fn, O_RDONLY | O_NONBLOCK);
  
  channel = g_io_channel_unix_new(in_fd);
  
  ch_id = g_io_add_watch(channel, G_IO_IN, (GIOFunc) read_watch,
                (gpointer) callback);
  printf("IOchannel ID: %d\n", ch_id);
}


void
close_comm()
{
  GError *error = NULL;
  
  g_io_channel_shutdown(channel, TRUE, &error);
}