/*
 * main.c
 * Copyright (C) Michael Heras 2018 <userxbw@gmail.com>
 *
        wmslides 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.

        wmslides 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/>.
 */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/timeb.h>
#include <X11/X.h>
#include <X11/xpm.h>
#include <X11/Xlib.h>
#include <Imlib2.h>

#include "wmgeneral.h"
#include "pixmaps.h"
#include "filelist.h"

#define CONFIGFILE ".wmslideshowrc"
#define VERSION "1.3.2"

char *path, *file;
int isize=64, dtime = 0, ordered = 0, ran = 0;

static void usage(char * pname)
{
    printf("%s Version: %s\n"
    "By Michael Heras <userxbw@gmail.com> (c) 2018\n\n"
    "\t-r, --random\t\t\t Shows images in random order.\n"
    "\t-o, --ordered\t\t\t Puts list into an ordered list.\n"
    "\t-p, --path [path to Images]\t images to be displayed.\n"
    "\t-f, --file [path to file]\t File with path and image files\n"
    "\t-t, --time [seconds]\t\t Delay time between images.\n"
    "Default time is 5 minutes.\n\n"
    "\nie:\n%s -t 30 -p /path/to/images\n"
    "%s -t 60 -r -f /path/to/file/filename\n", pname,VERSION, pname,pname);
}

static void ParseCMDLine(int argc, char *argv[])
{
    int i = 0;

    for (i=1; i < argc; i++)
    {
        if ( ((!strcmp(argv[i], "--path")) || (!strcmp(argv[i], "-p"))) && (i+1 < argc) )
        {
            path = argv[++i];
        }
        else if ( ((!strcmp(argv[i], "--time")) || (!strcmp(argv[i], "-t"))) && (i+1 < argc) )
        {
            dtime = atoi(argv[++i]);
        }
        else if (((!strcmp(argv[i], "--file")) || (!strcmp(argv[i], "-f"))) && (i+1 < argc) )
        {
            file = argv[++i];
        }
        else if ( ((!strcmp(argv[i], "--random")) || (!strcmp(argv[i], "-r"))))
        {
            ran = 1;
        }
        else if ( ((!strcmp(argv[i], "--ordered")) || (!strcmp(argv[i], "-o"))))
        {
            ordered = 1;
        }
        else
        {
            usage(argv[0]);
            exit(1);
        }
    }

    if ((argc < 3) )
    {
        usage(argv[0]);
        exit(1);
    }

}
void load_image(Imlib_Image image, Visual *visual,  Pixmap xpm, Window iconwin)
{
    visual = DefaultVisual(display, DefaultScreen(display));

    imlib_context_set_dither(1);
    imlib_context_set_display(display);
    imlib_context_set_visual(visual);

    //image = imlib_load_image(get_file_name());

    image = check_image_err(image);
    imlib_context_set_image(image);
    imlib_context_set_drawable(xpm);
    //check for good image
    //if bad image recall function to get
    //next image.
    if (image)
    {
        imlib_render_image_on_drawable_at_size(0, 0, isize, isize);
    }
    else
    {
        load_image(image, visual,  xpm, iconwin);
    }
    if (image)
    imlib_free_image();
    XSetWindowBackgroundPixmap (display, iconwin, xpm);
    XClearWindow (display,iconwin);
    XFlush (display);
    XSync (display, False);
}

void read_file(FILE *ptr, char *file)
{
    char * line = NULL;
    size_t len = 0;
    size_t big = 0;

    ptr = fopen(file, "r");
    if (ptr == NULL)
    {
        printf("Cannot Open File %s\n",file);
        exit(1);
    }
    while ((big = getline(&line, &len, ptr)) != -1)
    {
      //add null to end of line
        if ( (big>0 && line[big-1]=='\n') || (big>0 && line[big-1]=='\r') )
            line[--big]= 0x00;
        if ( check_file_ext(line) )
        {
            add_2_front(&filelist, line);
        }
    }
    fclose(ptr);
    free(line);
}

int main(int argc, char *argv[])
{
    extern int d_depth;
    extern Window iconwin, win;
    Visual *visual = NULL;
    Pixmap xpm;
    Imlib_Image image = NULL;
    FILE *fptr = NULL;

    ParseCMDLine(argc, argv);

    if (path)
    {
        printf("Loading Files\n");
        GetFiles(path,0);

        if ( get_length() == 0 )
        {
            printf("No Image Files \nFound to load\n"
                   "Check your Path to files\n"
                   "Exiting Program\n");
            return EXIT_FAILURE;
        }
    }

    if(file)
    {
        printf("Reading  File\n");
        read_file(fptr, file);

        if ( get_length() == 0)
        {
            printf("No Image Files \nFound to load\n"
                   "Check your file for proper formatting\n"
                   "Exiting Program\n");
            return EXIT_FAILURE;
        }
    }

    if ( ordered )
    {
        ran = 0; // to prevent setting both and having random showing of images
        filelist = list_sort(filelist, cmp_filename);
    }
    if ( dtime == 0 )
    {
        dtime = 300;
    }
    if ( ran )
    {
        prepare_filelist();
    }

    openXwindow(argc, argv, xpm_master, xpm_mask_bits, xpm_mask_width, xpm_mask_height);

    xpm = XCreatePixmap(display, win, 64, 64, d_depth);
    XFillRectangle(display, xpm, NormalGC, 0, 0, 64, 64);

    //load first image
    load_image(image, visual,xpm, iconwin);

    while (!sleep(dtime))
    {
        load_image(image, visual,xpm, iconwin);
    }
    //should never reach here
    return (0);
}
