require ("lfs")
local gtk = require("lgob.gtk")             -- Binding for GTK+
local gdk = require("lgob.gdk")             -- Binding for GDK
local gobj = require("lgob.gobject")             -- Binding for GObject

--function to open an image file chosen by user
function open_file()
	local dialog = gtk.FileChooserDialog.new("Select the file", window,
				gtk.FILE_CHOOSER_ACTION_OPEN, "gtk-cancel",
				gtk.RESPONSE_CANCEL, "gtk-ok", gtk.RESPONSE_OK)
	local filter1 = gtk.FileFilter.new()
	filter1:add_pattern("*.djvu")
	filter1:set_name("Djvu files")
	dialog:add_filter(filter1)

	local filter2 = gtk.FileFilter.new()
	filter2:add_pattern("*.*")
	filter2:add_pattern("*")	
	filter2:set_name("All files")
	dialog:add_filter(filter2)

	local response = dialog:run()

	dialog:hide()

	if response == -6 then
      	--do nothing
      	print ("User click Cancel.")
    else
    	filename =  dialog:get_filename()
		print (filename)
		cur_page = 1
		draw_page(cur_page)
  end
    
  dialog:destroy()

end


--global variables
FORMAT = "pnm"
img_width = 768
img_height = 900
filename = ""
pixbuf = nil
cur_page = 0
pageLabel = nil

function get_pixbuf_from_djvu(page_no)
	--g_sprintf(cmd, "ddjvu -format=%s -page=%d -size=%dx%d %s", 
		--			FORMAT, page_no, img_width, img_height, filename);
	local cmd = string.format('ddjvu -format=%s -page=%d -size=%dx%d \"%s\"',
								FORMAT, page_no, img_width, img_height, filename)

	print('cmd: '..cmd);
	
	local fp = io.popen(cmd)        -- runs command
	
	--FILE *fp = popen(cmd, "r");
	--guchar *file_buf;
	--size_t ret;

	local ret = 0
	local file_buf
	if (fp) then
		file_buf = fp:read("*a")          -- read output of command
		ret = #file_buf
		print("length of file_buf: "..ret)
		fp:close()
	end	
	print("2.1")
	local gpldr = gdk.PixbufLoader.new()	
	print("2.2")
	local success = gdk.PixbufLoader.write(gpldr, file_buf, ret, nil)
	print("2.3")
	if(success) then
		gdk.PixbufLoader.close(gpldr, nil)
		print("2.4")	
		print("2.5 success")
		pixbuf = gdk.PixbufLoader.get_pixbuf(gpldr)
		--g_object_ref(pixbuf);
--		if(gpldr!=NULL) g_object_unref(gpldr);
--			gpldr = NULL;
--		if(pixbuf==NULL){
--			printf("2.31 pixbuf==NULL\n");
--			//pixbuf = gdk_pixbuf_new_from_inline (-1, imanga_error_inline, FALSE, NULL);
--			//if(!error_icon_loaded) load_error_icon();
--			//return error_icon.pixbuf;
--			//exit(0);
--		}
--	}else{
--		g_printf( "497 gdk_pixbuf_loader_write not success\n");
--		g_object_unref(gpldr);
--		//pixbuf = gdk_pixbuf_new_from_inline (-1, imanga_error_inline, FALSE, NULL);
--		///if(!error_icon_loaded) load_error_icon();
--		//return error_icon.pixbuf;
--		//exit(0);
--	}
	else
		pixbuf = nil
	end
	print("2.6")

	return pixbuf
end

function draw_page(page_no)
	print ("in draw_page()...")
	local pixbuf = get_pixbuf_from_djvu(page_no)
	fg_image:set_from_pixbuf(pixbuf)
	pageLabel:set_label("Page: "..page_no)
end

function show_prevpage()
	print ("prevPage clicked.")
	if(cur_page>0) then
		local pn = cur_page
		draw_page(pn-1)
		cur_page = cur_page - 1
	end
end

function show_nextpage()
	print ("nextPage clicked.")
	local pn = cur_page
	draw_page(pn+1)
	cur_page = cur_page + 1
end

--main program start here
print ("Running djvu viewer...")

window = gtk.Window.new(gtk.WINDOW_TOPLEVEL)

window:set("title", "Lua Image Viewer", "window-position", gtk.WIN_POS_CENTER,
"app-paintable", true, "width-request", 768, "height-request", 935)

	-- Actions
	local a_open_file = gtk.Action.new("Open File", nil, "Open a file", "gtk-open")
	a_open_file:connect("activate", open_file)
	
	local a_quit = gtk.Action.new("Quit", nil, "Exit the application", "gtk-quit")
	a_quit:connect("activate", gtk.main_quit)
	
	local a_prevpage = gtk.Action.new("prevPage", "<-", "Prev page", nil)
	a_prevpage:connect("activate", show_prevpage)
	
	local a_nextpage= gtk.Action.new("nextPage", "->", "Next Page", nil)
	a_nextpage:connect("activate", show_nextpage)

	pageLabel = gtk.ToolButton.new(nil, nil)
	pageLabel:set_label("Page: #")

	-- Toolbar
	local toolbar = gtk.Toolbar.new()
	toolbar:add(a_open_file:create_tool_item())
	toolbar:add(gtk.SeparatorToolItem.new())
	
	toolbar:add(a_prevpage:create_tool_item())
	toolbar:add(pageLabel)
	toolbar:add(a_nextpage:create_tool_item())
	toolbar:add(a_quit:create_tool_item())
	
window:connect("delete-event", gtk.main_quit)

local vbox = gtk.VBox.new(false, 5)
buf = gdk.Pixbuf.new_from_file("djvu.jpg")
--fg_image = gtk.Image.new_from_pixbuf(buf)
fg_image = gtk.Image.new()
fg_image:set_from_pixbuf(buf)

local viewport = gtk.Viewport.new()
gtk.Container.add(viewport, fg_image);

--local scroll = gtk.ScrolledWindow.new()
--scroll:add_with_viewport(viewport)

vbox:pack_start(toolbar, false, false, 0)
vbox:pack_start(viewport, true, true, 0)

window:add(vbox)
window:show_all()
gtk.main()
