#!/usr/bin/env python
# encoding: utf-8

"""
Author
	takepy <takepyt@gmail.com>
	http://d.hatena.ne.jp/takepy/

License
	GPL (GNU General Public License)
	http://www.gnu.org/licenses/gpl.html

Version
	0.1 (First release version.)

"""

import wx, Image
import re, os

pop_global = 0
dirpath = "dirlist"

class Core():
	""" クラス分割する必要なし^^; """
	void = 0

	def addd(self,diganspath):
		global dirpath
		if not os.path.exists(dirpath):
			fw = open(dirpath, "w")
			fw.write(diganspath)
			fw.close()
			return
		fw = open(dirpath, "r")
		rb = fw.read()
		fw.close()
		chk = re.compile(diganspath)
		if re.search(chk, rb):
			self.void
		else:
			fw = open(dirpath, "w")
			fw.write(rb+"\n"+diganspath)
			fw.close()

	def addd_menu(self):
		global dirpath
		fw = open(dirpath, "r")
		rb = fw.read()
		fw.close()
		dirlist = rb.split("\n")
		"""
		for i in dirlist:
			self.dir = wx.Menu()
			id2 = wx.NewId()
			self.addd = wx.MenuItem(self.dir, id2, "Add Directory", "add directory", wx.ITEM_NORMAL)
			self.dir.AppendItem(self.addd)
			self.frame_1_menubar.Append(self.dir, "Directory")
			self.Bind(wx.EVT_MENU, self.addd_dig, self.addd)
"""

	def getimgpath(self,path):
		comp = re.compile(".*\.(jpg|JPG|jpeg|JPEG|BMP|bmp|png|PNG)$")
		path_list = []
		dir_list = []
		chk = 0
		for root, dirs, files in os.walk(path):
			print root, dirs, files
			files.sort()
			self.root_path = root
			for file in files:
				if 1:#re.match(".*("+path+")$",root):
					file_n = os.path.join(root, file)
					print file_n
					result = re.match(comp,file_n)
					if result:
						path_list.append(file_n)
						print file_n
				elif not re.match(".*("+path+")$",root) and chk != 1:
					dir_list.append(root)
					chk = 1
		print path_list, dir_list
		return path_list, dir_list
		

class MyFrame(wx.Frame):
	def __init__(self, *args, **kwds):
		# begin wx: MyFrame.__init__
		kwds["style"] = wx.DEFAULT_FRAME_STYLE
		wx.Frame.__init__(self, *args, **kwds)
		self.panel_1 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
		self.Menu()
		self.frame_2_statusbar = self.CreateStatusBar(1, 0)
		self.__set_properties()
		self.__do_layout()

		self.Bind(wx.EVT_CLOSE, self.close)

	def Menu(self):
		# Menu Bar
		## File
		self.menu = wx.Menu()
		id0 = wx.NewId()
		self.menu.Append(id0, "Exit", "")
		## Direcotory
		self.Menu2()
		## Help
		self.menu3 = wx.Menu()
		id4 = wx.NewId()
		id5 = wx.NewId()
		self.menu3.Append(id4, "Contact")
		self.menu3.AppendSeparator()
		self.menu3.Append(id5, "Information")
		## View
		self.menu4 = wx.Menu()
		id5 = wx.NewId()
		self.menu4.Append(id5, "Show DirectoryList", "Show the ListBox of Directory")
		## Menubar
		self.menubar = wx.MenuBar()
		self.menubar.Append(self.menu, "File")
		self.menubar.Append(self.menu2, "Directory")
		self.menubar.Append(self.menu4, "View")
		self.menubar.Append(self.menu3, "Help")
		## Set
		self.setmenubar = self.SetMenuBar(self.menubar)

		# Menu Bar end

		self.Bind(wx.EVT_MENU, self.close, id=id0)
		self.Bind(wx.EVT_MENU, self.showlistbox, id=id5)
		# end wx

	def showlistbox(self, event):
		frame_3 = MyFrame3(None, -1, "")
		frame_3.Show()

	def test(self, event):
		for line in range(len(self.bitmap_button)):
			self.bitmap_button[line].Destroy()
		self.panel_1.Destroy()
		self.panel_1 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
		self.panel_1.SetMinSize((1280, 700))
		self.panel_1.SetScrollRate(10, 10)
	
	def Menu2(self):
		self.menu2 = wx.Menu()
		id1 = wx.NewId()
		self.menu2.Append(id1, "Add Direcotry", "")
		self.menu2.AppendSeparator()
		self.FolderMenu()
		self.Bind(wx.EVT_MENU, self.addd_dig, id=id1)
		self.FolderMenubar()
		

	def addd_dig(self, event):
		core = Core()
		dig = wx.DirDialog(self, message="Please Choose Directory")
		digans = dig.ShowModal()
		diganspath = dig.GetPath()
		if digans == wx.ID_OK:
			core.addd(diganspath)
			self.OnceSetMenu(diganspath)

	def FolderMenu(self):
		global dirpath
		co = 770
		fw = open(dirpath, "r")
		for line in fw:
			vars()[co] = wx.NewId()
			line = re.compile("\n").sub("", line)
			self.menu2.Append(co, line)
			co += 1

	def FolderMenubar(self):
		global dirpath
		co = 770
		fw = open(dirpath,"r")
		for line in fw:
			self.Bind(wx.EVT_MENU, self.mkimglist, id=co)
			co += 1

	def OnceSetMenu(self, newdir):
		idonce = wx.NewId()
		self.menu2.Append(idonce, newdir)
		self.Bind(wx.EVT_MENU, self.mkimglist, id=idonce)

	def status(self):
		""" ステータスバー変更 """
		frame_2_statusbar_fields = ["Loading..."]
		for i in range(len(frame_2_statusbar_fields)):
			self.frame_2_statusbar.SetStatusText(frame_2_statusbar_fields[i], i)
		self.Show()
		""" End ステータスバー変更 """

	def status2(self):
		""" ステータスバー """
		frame_2_statusbar_fields = ["Complete"]
		for i in range(len(frame_2_statusbar_fields)):
			self.frame_2_statusbar.SetStatusText(frame_2_statusbar_fields[i], i)
		self.Show()
		""" End ステータスバー """

	def mkimglist(self, event):
		self.status()
		try:
			""" Delete BTbuttons, Panel """
			for line in range(len(self.bitmap_button)):
				self.bitmap_button[line].Destroy()
			self.panel_1.Destroy()
			self.panel_1 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
			self.panel_1.SetMinSize((1280, 700))
			self.panel_1.SetScrollRate(10, 10)
		except AttributeError:
			print "First transaction."
		"""  """
		core = Core()
		menuid = event.GetId()
		menuobj = event.GetEventObject()
		menulabel = menuobj.GetLabel(menuid)
		print "call", menulabel
		path_list, dir_list = core.getimgpath(menulabel)
		self.Img(path_list, dir_list)

	def mkimglist2(self, menulabel):
		self.status()
		try:
			""" Delete BTbuttons, Panel """
			for line in range(len(self.bitmap_button)):
				self.bitmap_button[line].Destroy()
			self.panel_1.Destroy()
			self.panel_1 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
			self.panel_1.SetMinSize((1280, 700))
			self.panel_1.SetScrollRate(10, 10)
		except AttributeError:
			print "First transaction."
		"""  """
		core = Core()
		print "call", menulabel
		path_list, dir_list = core.getimgpath(menulabel)
		self.Img(path_list, dir_list)

	def Img(self,img_list, dir_list):
		global image_list_global
		self.bitmap_button = []
		self.sizer_1 = wx.BoxSizer(wx.VERTICAL)
		self.sizer_2 = wx.BoxSizer(wx.VERTICAL)
		self.grid_sizer_1 = wx.GridSizer(8, 8, 0, 0)
		cox, coy, count = 0, 0, 0
		h = 200
		w = 150
		image_list_global = img_list
		for tmp in img_list:
			print "!",
			pil = Image.open(tmp)
			pil.thumbnail((w,h), Image.ANTIALIAS)
			img = wx.EmptyImage(pil.size[0], pil.size[1])
			img.SetData(pil.convert('RGB').tostring())
			self.bitmap_button.append(wx.BitmapButton(self.panel_1, -1, img.ConvertToBitmap()))
			self.Bind(wx.EVT_BUTTON, self.pop, self.bitmap_button[count])
			self.bitmap_button[count].SetMinSize((w, h))
			self.bitmap_button[count].SetLabel(str(count))
			self.grid_sizer_1.Add(self.bitmap_button[count], 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
			print self.bitmap_button[count]
			count += 1
		self.panel_list = []
		count = 0
		for tmp in range(30 - len(img_list)):
			self.panel_list.append(wx.Panel(self, -1))
			self.grid_sizer_1.Add(self.panel_list[count], 1, wx.SUNKEN_BORDER, 0)
			print tmp
			count += 1
		self.panel_1.SetSizer(self.grid_sizer_1)
		self.sizer_2.Add(self.panel_1, 1, wx.EXPAND, 0)
		self.sizer_1.Add(self.sizer_2, 1, wx.EXPAND, 0)
		self.SetSizer(self.sizer_1)
		self.Layout()
		self.status2()

	def __set_properties(self):
		# begin wx: MyFrame.__set_properties
		self.SetTitle("Manga Viewer")
		self.SetSize((1280, 768))
		self.panel_1.SetMinSize((1280, 768))
		icon = wx.EmptyIcon()
		icon.CopyFromBitmap(wx.Bitmap("./etc/asou.png", wx.BITMAP_TYPE_ANY))
		self.SetIcon(icon)
		self.panel_1.SetScrollRate(10, 10)
		# end wx

	def __do_layout(self):
		# begin wx: MyFrame.__do_layout
		self.frame_2_statusbar.SetStatusWidths([-1])
		# statusbar fields
		frame_2_statusbar_fields = ["Complete"]
		for i in range(len(frame_2_statusbar_fields)):
			self.frame_2_statusbar.SetStatusText(frame_2_statusbar_fields[i], i)
		print "start"# end wx

	def pop(self, event): # wx: MyFrame.<event_handler>
		global pop_global
		id = event.GetId()
		obj = event.GetEventObject()
		label = obj.GetLabel()
		print label, pop_global, "test"
		if pop_global == 1:
			print "call not new"
			if self.dig:
				self.dig.test(label)
		elif pop_global == 0:
			print "call new"
			self.dig = MyFramePop(None, -1, "")
			self.dig.Show()
			self.dig.test(label)
			pop_global = 1

	def close(self, event):
		exit()

	def getpath(self, event):
		event.Skip()

# end of class MyFrame


class MyFramePop(wx.Frame):
	def __init__(self, *args, **kwds):
		# begin wx: MyFramePop.__init__
		kwds["style"] = wx.DEFAULT_FRAME_STYLE
		wx.Frame.__init__(self, *args, **kwds)
		
#		self.bitmap_button_3 = wx.BitmapButton(self, -1, wx.Bitmap(MyFrame.img_list[id], wx.BITMAP_TYPE_ANY))
#		self.bitmap_button_4 = wx.BitmapButton(self, -1, wx.Bitmap("/home/alice/Firefox_wallpaper.png", wx.BITMAP_TYPE_ANY))

		self.__set_properties()
		self.__do_layout()
		self.Bind(wx.EVT_CLOSE, self.close)

#		self.Bind(wx.EVT_BUTTON, self.next, self.bitmap_button_3)
#		self.Bind(wx.EVT_BUTTON, self.back, self.bitmap_button_4)
		# end wx
	h = 900
	check,check2 = 0,0
	def close(self, event):
		global pop_global
		pop_global = 0
		self.Destroy()
	def __set_properties(self):
		# begin wx: MyFramePop.__set_properties
		self.SetTitle("View")
		self.SetSize((1280, self.h))
		self.SetBackgroundColour(wx.Colour(234, 232, 227))
		icon = wx.EmptyIcon()
		icon.CopyFromBitmap(wx.Bitmap("./etc/asou.png", wx.BITMAP_TYPE_ANY))
		self.SetIcon(icon)
#		self.bitmap_button_3.SetMinSize((640, 768))
#		self.bitmap_button_4.SetMinSize((640, 768))
		# end wx

	def __do_layout(self):
		# begin wx: MyFramePop.__do_layout
#		sizer_3 = wx.BoxSizer(wx.VERTICAL)
#		sizer_4 = wx.BoxSizer(wx.VERTICAL)
#		sizer_5 = wx.BoxSizer(wx.HORIZONTAL)
#		sizer_5.Add(self.bitmap_button_3, 0, 0, 0)
#		sizer_5.Add(self.bitmap_button_4, 0, 0, 0)
#		sizer_4.Add(sizer_5, 1, wx.EXPAND, 0)
#		sizer_3.Add(sizer_4, 0, 0, 0)
#		self.SetSizer(sizer_3)
		self.Layout()
		# end wx
	def test(self, id):
		print self.check,self.check2,id
		""" ここらの処理酷すぎ。できるだけtryを使わないように。 """
		try:
			self.bitmap_button_3.Destroy()
			self.bitmap_button_4.Destroy()
		except AttributeError:
			print "First call."
		try:
			pil = Image.open(image_list_global[int(id)+1])
			pil.thumbnail((640,self.h), Image.ANTIALIAS)
			img = wx.EmptyImage(pil.size[0], pil.size[1])
			img.SetData(pil.convert('RGB').tostring())
			pil = Image.open(image_list_global[int(id)])
			pil.thumbnail((640,self.h), Image.ANTIALIAS)
			img2 = wx.EmptyImage(pil.size[0], pil.size[1])
			img2.SetData(pil.convert('RGB').tostring())
		except IndexError:
			try:
				print "call img2"
				pil = Image.open(image_list_global[int(id)])
				pil.thumbnail((640,self.h), Image.ANTIALIAS)
				img2 = wx.EmptyImage(pil.size[0], pil.size[1])
				img2.SetData(pil.convert('RGB').tostring())
				print "call img"
				pil = Image.open(image_list_global[int(0)])
				pil.thumbnail((640,self.h), Image.ANTIALIAS)
				img = wx.EmptyImage(pil.size[0], pil.size[1])
				img.SetData(pil.convert('RGB').tostring())
				id = "-1"
			except IndexError:
				id = 0
				print "call img2"
				pil = Image.open(image_list_global[int(id)])
				pil.thumbnail((640,self.h), Image.ANTIALIAS)
				img2 = wx.EmptyImage(pil.size[0], pil.size[1])
				img2.SetData(pil.convert('RGB').tostring())
				print "call img"
				pil = Image.open(image_list_global[int(0)])
				pil.thumbnail((640,self.h), Image.ANTIALIAS)
				img = wx.EmptyImage(pil.size[0], pil.size[1])
				img.SetData(pil.convert('RGB').tostring())
		self.bitmap_button_3 = wx.BitmapButton(self, -1, img.ConvertToBitmap())
		self.bitmap_button_4 = wx.BitmapButton(self, -1, img2.ConvertToBitmap())
		self.Bind(wx.EVT_BUTTON, self.next, self.bitmap_button_3)
		self.Bind(wx.EVT_BUTTON, self.back, self.bitmap_button_4)
		self.bitmap_button_3.SetMinSize((640, self.h))
		self.bitmap_button_4.SetMinSize((640, self.h))
		self.bitmap_button_3.SetLabel(id)
		self.bitmap_button_4.SetLabel(str(int(id)+1))

		sizer_3 = wx.BoxSizer(wx.VERTICAL)
		sizer_4 = wx.BoxSizer(wx.VERTICAL)
		sizer_5 = wx.BoxSizer(wx.HORIZONTAL)
		sizer_5.Add(self.bitmap_button_3, 0, 0, 0)
		sizer_5.Add(self.bitmap_button_4, 0, 0, 0)
		sizer_4.Add(sizer_5, 1, wx.EXPAND, 0)
		sizer_3.Add(sizer_4, 0, 0, 0)
		self.SetSizer(sizer_3)
		self.Layout()
		"""
		# 画像を一度に縮小しリストから呼び出す
		if self.check == 0:
			pil = Image.open(image_list_global[int(id)])
			pil.thumbnail((640,self.h), Image.ANTIALIAS)
			onceimg = wx.EmptyImage(pil.size[0], pil.size[1])
			onceimg.SetData(pil.convert('RGB').tostring())
			self.bitmap_button_3 = wx.BitmapButton(self, -1, onceimg.ConvertToBitmap())
			self.bitmap_button_4 = wx.BitmapButton(self, -1, onceimg.ConvertToBitmap())
			self.Bind(wx.EVT_BUTTON, self.next, self.bitmap_button_3)
			self.Bind(wx.EVT_BUTTON, self.back, self.bitmap_button_4)
			self.bitmap_button_3.SetMinSize((640, self.h))
			self.bitmap_button_4.SetMinSize((640, self.h))
			self.bitmap_button_3.SetLabel(str(id))
			self.bitmap_button_4.SetLabel(str(int(id)+1))
			sizer_3 = wx.BoxSizer(wx.VERTICAL)
			sizer_4 = wx.BoxSizer(wx.VERTICAL)
			sizer_5 = wx.BoxSizer(wx.HORIZONTAL)
			sizer_5.Add(self.bitmap_button_3, 0, 0, 0)
			sizer_5.Add(self.bitmap_button_4, 0, 0, 0)
			sizer_4.Add(sizer_5, 1, wx.EXPAND, 0)
			sizer_3.Add(sizer_4, 0, 0, 0)
			self.SetSizer(sizer_3)
			self.Layout()
			self.Show()
			self.img = []
			for line in range(len(image_list_global)):
				pil = Image.open(image_list_global[line])
				pil.thumbnail((640,self.h), Image.ANTIALIAS)
				self.img.append(wx.EmptyImage(pil.size[0], pil.size[1]))
				self.img[line].SetData(pil.convert('RGB').tostring())
				print line
			self.check += 1
		else:
			print self.img[int(id)]
			self.bitmap_button_3 = wx.BitmapButton(self, -1, self.img[int(id)+1].ConvertToBitmap())
			self.bitmap_button_4 = wx.BitmapButton(self, -1, self.img[int(id)].ConvertToBitmap())
			self.Bind(wx.EVT_BUTTON, self.next, self.bitmap_button_3)
			self.Bind(wx.EVT_BUTTON, self.back, self.bitmap_button_4)
			self.bitmap_button_3.SetMinSize((640, self.h))
			self.bitmap_button_4.SetMinSize((640, self.h))
			self.bitmap_button_3.SetLabel(id)
			self.bitmap_button_4.SetLabel(str(int(id)+1))
			sizer_3 = wx.BoxSizer(wx.VERTICAL)
			sizer_4 = wx.BoxSizer(wx.VERTICAL)
			sizer_5 = wx.BoxSizer(wx.HORIZONTAL)
			sizer_5.Add(self.bitmap_button_3, 0, 0, 0)
			sizer_5.Add(self.bitmap_button_4, 0, 0, 0)
			sizer_4.Add(sizer_5, 1, wx.EXPAND, 0)
			sizer_3.Add(sizer_4, 0, 0, 0)
			self.SetSizer(sizer_3)
			self.Layout()
"""
	def next(self, event): # wx: MyFramePop.<event_handler>
		print "call next"
		id = event.GetId()
		obj = event.GetEventObject()
		label = obj.GetLabel()
		self.test(str(int(label)+2))

	def back(self, event):
		print "call back"
		id = event.GetId()
		obj = event.GetEventObject()
		label = obj.GetLabel()
		self.test(str(int(label)-3))

# end of class MyFramePop

class MyFrame3(wx.Frame):
	def __init__(self, *args, **kwds):
		# begin wx: MyDialog.__init__
		kwds["style"] = wx.DEFAULT_FRAME_STYLE
		wx.Frame.__init__(self, *args, **kwds)
		choice = self.makelist()
		self.list_box_1 = wx.ListBox(self, -1, choices=choice, style=wx.LB_SINGLE|wx.LB_HSCROLL|wx.LB_SORT)
		self.button_3 = wx.Button(self, wx.ID_ADD, "Add", style=wx.ALIGN_RIGHT)
		self.button_4 = wx.Button(self, wx.ID_DELETE, "Delete", style=wx.ALIGN_RIGHT)

		self.__set_properties()
		self.__do_layout()

		self.Bind(wx.EVT_LISTBOX, self.list, self.list_box_1)
		# end wx

	def makelist(self):
		global dirpath
		fw = open(dirpath, "r")
		fb = fw.read().split("\n")
		fw.close()
		choice = []
		self.choice_path = []
		for line in fb:
			if not line == "":
				dirname = str(line).split("/")[-1]
				choice.append(dirname)
				self.choice_path.append(line)
		return choice

	def __set_properties(self):
		# begin wx: MyDialog.__set_properties
		self.SetTitle("dialog_1")
		_icon = wx.EmptyIcon()
		_icon.CopyFromBitmap(wx.Bitmap("./etc/asou.png", wx.BITMAP_TYPE_ANY))
		self.SetIcon(_icon)
		self.SetSize((216, 300))
		self.list_box_1.SetMinSize((216, 270))
		self.list_box_1.SetSelection(0)
		self.button_3.SetMinSize((108, 30))
		self.button_4.SetMinSize((108, 30))
		# end wx

	def __do_layout(self):
		# begin wx: MyDialog.__do_layout
		sizer_2 = wx.BoxSizer(wx.VERTICAL)
		grid_sizer_1 = wx.GridSizer(1, 2, 0, 0)
		sizer_2.Add(self.list_box_1, 0, 0, 1)
		grid_sizer_1.Add(self.button_3, 0, 0, 0)
		grid_sizer_1.Add(self.button_4, 0, 0, 0)
		sizer_2.Add(grid_sizer_1, 1, wx.EXPAND, 0)
		self.SetSizer(sizer_2)
		self.Layout()
		# end wx

	def list(self, event): # wx: MyDialog.<event_handler>
		id = event.GetSelection()
		print id, self.choice_path[id]


class MyApp(wx.PySimpleApp):
	def OnInit(self):
		wx.InitAllImageHandlers()
		frame_1 = MyFrame(None, -1, "")
		self.SetTopWindow(frame_1)
		frame_1.Show()
		return 1

# end of class MyApp

if __name__ == "__main__":
	app = MyApp(0)
	app.MainLoop()
