
#include <stdio.h>

#include "file_entry.h"

#include "mecha.h"

static char * file_entry_create_display_name (FileEntry *instance);

static int g_file_sequence_counter = 0;

struct s_FileEntry
{
    int fileno;
    char * filename;
    char * displayName;
};

FileEntry *
file_entry_new (const char *filename)
{
    FileEntry *instance = (FileEntry *) malloc (sizeof (FileEntry));

    instance->fileno = g_file_sequence_counter++;

    instance->filename = strFcopy (filename);

    instance->displayName = file_entry_create_display_name (
            instance);

    return (instance);
}

void
file_entry_destroy (void *ptr)
{
    FileEntry *instance = (FileEntry *) ptr;

    free (instance->filename);

    free (instance->displayName);

    free (instance);
}

FileEntry *
file_entry_duplicate (FileEntry *instance)
{
    FileEntry *dest = (FileEntry *) malloc (sizeof (FileEntry));

    dest->fileno = instance->fileno;
    dest->filename = strFcopy (instance->filename);
    dest->displayName = strFcopy (instance->displayName);

    return (dest);
}

const char *
file_entry_get_filename (FileEntry *instance)
{
    return (instance->filename);
}

const char *
file_entry_get_display_name (FileEntry *instance)
{
    return (instance->displayName);
}

int
file_entry_get_fileno (FileEntry *instance)
{
    return (instance->fileno);
}

static char *
file_entry_create_display_name (FileEntry *instance)
{
   const char *p, *q;
   char *ret;
   int len;

   p = strrchr (instance->filename, '/');

   if (p != NULL)
   {
      p++;
   }
   else
   {
       p = instance->filename;
   }

   q = strrchr (p, '.');

   if (q)
   {
       len = q - p;
   }
   else
   {
       len = strlen (p);
   }

   ret = (char *) malloc (len + 1);
   memcpy (ret, p, len);
   ret[len] = 0;

   return (ret);
}

