# -*- coding: utf-8 -*-
""" Parser image from 2ch """

import urllib
import json
from Tkinter import *
import ttk


def check_value(er=1):
    if not entry1.get():
        label1['text'] = u"Enter url"
    elif not '2ch.hk' in entry1.get():
        label1['text'] = u"Enter url 2ch.hk v1"
    else:
        parser()

def parser():
    try:
        urli = entry1.get().replace('html','json')
        req = json.load(urllib.urlopen(urli))
        thread = req['threads'][0]['posts']
        
        l = []
        for x in thread:
            if ('files' in x) and (('png' in x['files'][0]['path']) or ('jpg' in x['files'][0]['path'])):
                l.append(urli[:urli.index('hk/')+3] + urli[urli.index('hk/')+3:].split('/',1)[0] + '/' + x['files'][0]['path'])
                #print  urli[:urli.index('hk/')+3] + urli[urli.index('hk/')+3:].split('/',1)[0] + '/' + x['files'][0]['path']
                label1['text'] = 'open ' + str(urli[:urli.index('hk/')+3] + urli[urli.index('hk/')+3:].split('/',1)[0] + '/' + x['files'][0]['path'])
                root.update()
        for x in l:
            label1['text'] = 'download ' + str(x) 
            urllib.urlretrieve(x, x.rsplit('/',1)[1])
            root.update()

    
        label1.configure(text = "Good work")
    
        #label1.after(200, label1.configure(text = "Enter url"))

        #label1.after(2000, label1.configure(text = "Enter url"))
        root.update()
    except:
         label1['text'] = "Dont open url"
        



root=Tk()
root.title("2ch parser image")
root.minsize(width = 300, height = 185)

fra1 = Frame(root,width=300,height=30)
fra1.pack()

# input field------------------------------------------------

#text1=Text(root,height=7,width=7,font='Arial 14',wrap=WORD)
entry1 = Entry(root, width=25, font='Arial 14')
entry1.focus()
entry1.bind('<Return>', check_value)
entry1.pack()#pack


# output field------------------------------------------------
label1 = Label(root, text = u"Enter url", font='arial 7', relief ='groove', width=46)
label1.pack()#pack


fra2 = Frame(root,width=300,height=30)
fra2.pack()


# button------------------------------------------------------
button1 = Button(root, text=u"parser",font='arial 12', command=check_value)

button1.pack()#pack


fra3 = Frame(root,width=300,height=30)
fra3.pack()

label2 = Label(root, text = u"s0k1ll", font='arial 7')
label2.pack(side='left')#pack
# run main loop-----------------------------------------------
root.mainloop()
