/* filelist.c

Copyright (C) 1999-2003 Tom Gilbert.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies of the Software and its documentation and acknowledgment shall be
given in the documentation and software packages that this Software was
used.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
imPLIED, INCLUDING BUT NOT LimITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS BE LIABLE FOR ANY CLAim, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

//aug 10 2017

Modifactions made by me.
Same permissions are passed on as formentioned pertaining to the
modifactions made by me.
Copyright (C) 2017 - ... Michael Hearas.

*/
//aug 10 2017
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <time.h>

// get pid
#include <sys/types.h>
#include <unistd.h>
// end

#include "strjoin.h"
#include "filelist.h"

mylist* filelist = NULL;
mylist *ret = NULL;



/*
void check_image_err(void)
{
Imlib_Load_Error err;
char *filename;

filename = get_file_name();

printf("filename %s\n", filename);

if(filename == NULL)
{
    printf("File null\n");
    exit(1);
}

 im.image = imlib_load_image_with_error_return(filename, &err);

if (err)
{

    //spit out image path and name
   printf("Bad Image: %s\n", filename);
  // get next image
   check_image_err();


}

if(im.image == NULL)
{
    printf("No Image\n");
    exit(1);
}
}

*/

char *get_file_name(void)
{
    ret = list_time_jump(ret,1);
    //printf("%s\n", ret->filename);
    return (ret->filename);
}

mylist *list_time_jump(mylist *l, int num)
{

    int i;


    if(l)
        ret = l;
    else
        ret = filelist;
    //limits it movement
    for (i = 0; i < num; i++)
    {
        if (ret->next)
        {
            ret = ret->next;
        }
        else
        {
            ret = filelist;
        }
    }
    return (ret);
}

mylist * list_new(void)
{
   mylist *l;

   l = (mylist *) malloc(sizeof(mylist));
   l->filename = NULL;
   l->listcount = 0;
   l->next = NULL;
   l->prev = NULL;
   return (l);
}


void add_2_front(mylist** filelist, char *filename)
{
    mylist* new_file = (mylist *)malloc(sizeof(mylist));
    new_file->filename = strdup(filename);
    new_file->listcount = 0;

    if(!(*filelist)){
        new_file->next = NULL;
        (*filelist) = new_file;
    }else{
        new_file->next = (*filelist);
        (*filelist) = new_file;
    }
 return;
}


void insertNode(mylist** head, char *filename, int c)
{
    while (*head && strcmp((*head)->filename, filename) < 0)
        head = &(*head)->next;

    mylist *p = (mylist *) malloc(sizeof *p);
    p->filename = strdup(filename);
    p->listcount = c;
    p->next = *head;
    *head = p;
}


char *get_im_name(void)
{
    mylist* curr  = filelist;

    //get current file in list
        if(curr->filename)
        {
            return (curr->filename);
        }
        else
        {
            curr = curr->next;
        }

    return(curr->filename);

}

char *get_number_in_list(int numberfile)
{
    int ln;
    mylist* current = filelist;
    ln = list_length(filelist);

if(numberfile > ln)
{
    printf("number ( %d ) larger than list length\n", numberfile);
    exit(1);
}

while (1)
{

    if (current->listcount == numberfile)
    {
        return(current->filename);
    }

   if(current->next)
     current = current->next;
    else
      current = filelist;

  }
}


char *get_absolute_path(char *path)
{

    char cwd[PATH_MAX];
    char fullpath[PATH_MAX];
    char temp[PATH_MAX];
    char *ret;

    if (!path)
        return(NULL);
    if (path[0] == '/' )
        return(strdup(path));
    /* This path is not relative. We're gonna convert it, so that a
       filelist file can be saved anywhere and feh will still find the
       images */

    /* I SHOULD be able to just use a simple realpath() here, but dumb *
       old Solaris's realpath doesn't return an absolute path if the
       path you give it is relative. Linux and BSD get this right... */
    if (getcwd(cwd, sizeof(cwd)) == NULL)
        printf("Cannot determine working directory:");
    snprintf(temp, sizeof(temp), "%s/%s", cwd, path);
    if (realpath(temp, fullpath) != NULL) {
        ret = strdup(fullpath);
    } else {
        ret = strdup(temp);
    }

    return(ret);
}
/* Recursive */
void add_file_to_filelist_recursively(char *origpath, unsigned char level)
{
    struct stat st;
    char *path;
    int recursive = 1;
    char *name1;
    char *name2;


    if (!origpath)
        return;

    path = strdup(origpath);
  //  printf("orginal path %s\n",origpath);

    if (level == FILELIST_FIRST)
    {
        /* First time through, sort out pathname */
        int len = 0;

        len = strlen(path);
        if (path[len - 1] == '/')
            path[len - 1] = '\0';

    char *newpath = get_absolute_path(path);

            free(path);
            path = newpath;

    }

    errno = 0;
    if (stat(path, &st))

    {
        printf("bad path %s\n", path);
        free(path);
        exit(1);
    }

        if ((S_ISDIR(st.st_mode)) && (level != FILELIST_LAST)) {
        struct dirent **de;
        DIR *dir;
        int cnt, n;

        if ((dir = opendir(path)) == NULL)
        {
            printf("couldn't open directory %s:", path);
            free(path);
            return;
        }

        n = scandir(path, &de, NULL, NULL);
        if (n < 0) {
            switch (errno) {
            case ENOMEM:
                printf("Insufficient memory to scan directory %s:", path);
                break;
            default:
                printf("Failed to scan directory %s:", path);
            }
        } else
        {
            for (cnt = 0; cnt < n; cnt++) {
                if (strcmp(de[cnt]->d_name, ".")
                        && strcmp(de[cnt]->d_name, ".."))
                        {
                            char *newfile;
                            name1 =  strdup(de[cnt]->d_name);
                          //  check_file_ext(name1);
                          //printf("im.name1 %s\n",im.name1);

                            name1 = remove_ext(name1, '.' , '/');
                            name2 =  strdup(name1);
                            name2 =  remove_back(name2);

                        //    printf("RETURNED:::: %s\n", im.name2);

                            name2 = removeChar(name2, '-');


                            newfile = strjoin("", path, "/", de[cnt]->d_name, NULL);
                         //  printf("add_2_front %s newfile %s\n", path, newfile);

                    //gets recursive always
                    if (recursive)
                    {

                        add_file_to_filelist_recursively(newfile, FILELIST_CONTINUE);
                    }
                    else

                        add_file_to_filelist_recursively(newfile, FILELIST_LAST);
                        free(newfile);
                }
                free(de[cnt]);
            }
            free(de);
        }
        closedir(dir);
    }
    else if (S_ISREG(st.st_mode))
    {

        add_2_front(&filelist, path);
    }
    free(path);
    return;
}

void add_file_count(mylist* filelist)
{
    mylist* current = filelist;
    int count = 1;
    while(current)
    {
        current->listcount = count;
        current = current->next;
        count++;
    }
}

void display_list(mylist* filelist)
{
    mylist* current_node = filelist;
    printf("Linked List:\n");
    while(current_node){
        printf("[%d]->%s\n", current_node->listcount, current_node->filename);
        current_node = current_node->next;
    }
    printf("NULL\n");
}

int check_file_ext(char *name1)
{
    printf("im.name1 %s\n", name1);
    return 1;
}

int list_length(mylist * l)
{
   int length;

   length = 0;
   while (l)
   {
      length++;
      l = l->next;
   }
   return (length);
}

void get_length(void)
{
    printf("list_length %d\n", list_length(filelist));
}

void prepare_filelist(void)
{
    filelist = list_randomize(filelist);
}

mylist *  list_randomize(mylist * list)
{
    int len, r, i;
    mylist **farray, *f, *t;

   if (!list)
      return (NULL);
   len = list_length(list);

   if (len <= 1)
      return (list);
   farray = (mylist **) malloc(sizeof(mylist *) * len);
   for (f = list, i = 0; f; f = f->next, i++)
   {
      farray[i] = f;
   }
   srand(getpid() * time(NULL) % ((unsigned int) -1));
   for (i = 0; i < len - 1; i++)
   {
     r = i + rand() / (RAND_MAX / (len - i) + 1 );
      t = farray[r];
      farray[r] = farray[i];
      farray[i] = t;
   }
   list = farray[0];
   list->prev = NULL;
   list->next = farray[1];
   for (i = 1, f = farray[1]; i < len - 1; i++, f = f->next)
   {
      f->prev = farray[i - 1];
      f->next = farray[i + 1];
   }
   f->prev = farray[len - 2];
   f->next = NULL;
   free(farray);
   return (list);
}


void remove_link(mylist** head, char *value_to_remove)
{
    mylist* temp_node = NULL;
    mylist* current_node = (*head);
    if((*head)->filename == value_to_remove){
        (*head) = (*head)->next;
    }else{
        while(current_node){
            if(current_node->filename == value_to_remove)
{
                temp_node = current_node->next;
                current_node->next = NULL;
                current_node = temp_node;
            }
            current_node = current_node->next;
        }
    }
    return;
}

void free_file(mylist *file)
{
    if (!file)
        return;
    if(file->filename)
        free(file->filename);

    free(file);
    return;
}


mylist* list_unlink(mylist * root, mylist * l)
{
   if (!l)
      return (root);

   if ((!root) || ((l == root) && (!l->next)))
      return (NULL);

   if (l->prev)
      l->prev->next = l->next;
   if (l->next)
      l->next->prev = l->prev;
   if (root == l)
      root = root->next;
   return (root);
}

mylist * list_move_down_by_one(mylist * root, mylist * l)
{
   mylist *temp;

   if (!l || !l->next)
      return (root);

   // store item we link next to
   temp = l->next;
   // remove from list
   root = list_unlink(root, l);
   // add back one before
   l->next = temp->next;
   l->prev = temp;
   if (temp->next)
      temp->next->prev = l;
   temp->next = l;

   return (root);
}


mylist * list_add_end(mylist * root, char *filename, int c)
{
   mylist *l, *last;
   int ln;
   ln = list_length(root);
   ln += root->listcount + 1;

   last = list_last(root);
   l = list_new();
   l->prev = last;
   l->filename = filename;
   l->listcount = ln;
   if (last)
   {
      last->next = l;
      return (root);
   }
   else
   {
      return (l);
   }
}

mylist * list_last(mylist * l)
{
   if (l)
   {
      while (l->next)
         l = l->next;
   }
   printf("list_last, %s\n", l->filename);
   return (l);
}



// sorted List functions
// how to call it.
/*
 filelist = list_sort(filelist, cmp_filename);
 */


int cmp_filename(mylist *file1, mylist *file2)
{
    return(strcmp(file1->filename, file2->filename));
}



mylist *list_sort(mylist * list, compare_fn cmp)
{
   mylist *l1, *l2;

   if (!list)
      return (NULL);
   if (!list->next)
      return (list);

   l1 = list;
   l2 = list->next;

   while ((l2 = l2->next) != NULL)
   {
      if ((l2 = l2->next) == NULL)
         break;
      l1 = l1->next;
   }
   l2 = l1->next;
   l1->next = NULL;

   return (list_sort_merge
           (list_sort(list, cmp), list_sort(l2, cmp), cmp));
}

mylist *list_sort_merge(mylist * l1, mylist * l2 , compare_fn cmp)
{
   mylist list, *l, *lprev;

   l = &list;
   lprev = NULL;

   while (l1 && l2)
   {
      if (strcmp(l1->filename, l2->filename) < 0)
      {
         l->next = l1;
         l = l->next;
         l->prev = lprev;
         lprev = l;
         l1 = l1->next;
      }
      else
      {
         l->next = l2;
         l = l->next;
         l->prev = lprev;
         lprev = l;
         l2 = l2->next;
      }
   }
   l->next = l1 ? l1 : l2;
   l->next->prev = l;

   return (list.next);
}
char *remove_ext (char* mystr, char dot, char sep)

{
    char *retstr, *lastdot, *lastsep;

    // Error checks and allocate string.

    if (mystr == NULL)
        return NULL;
    if ((retstr = malloc (strlen (mystr) + 1)) == NULL)
        return NULL;

    // Make a copy and find the relevant characters.

    strcpy (retstr, mystr);
    lastdot = strrchr (retstr, dot);
    lastsep = (sep == 0) ? NULL : strrchr (retstr, sep);

    // If it has an extension separator.

    if (lastdot != NULL) {
        // and it's before the extenstion separator.

        if (lastsep != NULL) {
            if (lastsep < lastdot) {
                // then remove it.

                *lastdot = '\0';
            }
        } else {
            // Has extension separator with no path separator.

            *lastdot = '\0';
        }
    }

    // Return the modified string.

    return retstr;
}

char *remove_back(char *front)
{
    char *frontTemp , *returnEnd;

    if (front == NULL)
        return NULL;

    frontTemp = malloc (strlen (front) + 1);

    strcpy (frontTemp, front);
    // chop off 11 chars at front
    returnEnd = frontTemp + 11;

    return (returnEnd);
}


char *removeChar( char * string, char letter )
{

      for( unsigned int i = 0; i < strlen( string ); i++ )

        if( string[i] == letter )
        {
            strcpy( string + i, string + i + 1 );
        }
    return (string);
    }
