# -*- coding: cp936 -*-
from os import system as do
from urllib2 import urlopen
from urllib import quote
from time import ctime
import sys
def shorten_url(url):
    print ">>Shortening URL..."
    try:
        vgd_result = urlopen('http://v.gd/create.php?format=simple&url='+quote(url)).read()
    except:
        return url #sorry....
    else:
        if vgd_result.startswith('http://v.gd/'):
            return vgd_result
        #else
    return url
web_keywords=["http://","https://"]
url_blocked=['&']
fila = open('task.txt','r')
tasks = fila.readlines()
fila.close()
for i in range(len(tasks)):
    tasks[i] = tasks[i][0:len(tasks[i])-1]
def size():
    width=80
    height=0
    for i in range(len(tasks)):#init visible tasks
        lenth=len(tasks[i])/width
        if lenth*width<len(tasks[i]):#手动进位来代替截断
            lenth=lenth+1
        height=height+lenth
    do('mode con cols='+str(width)+' lines='+str(height+3))#set console size based on the two factors
def web_open(fing):
    if fing.startswith('[WEB]') :
        temp=fing.lower().find("http://")
        if fing.endswith('(!)'):
            do('start '+fing[temp:-3])
        else:
            do('start '+fing[temp:])
def save():
    fila = open('task.txt','w+')
    for i in tasks :
        fila.write(i)
        fila.write('\n')
    fila.close()
def process(cmd):
    if cmd=='':
        return -1
    else:
        if cmd[0]=='/':
            try :
                fing = int(cmd[1:len(cmd)])
            except :
                pass
            else :
                if tasks[fing][len(tasks[fing])-3:len(tasks[fing])] == '(!)':
                    tasks[fing] = tasks[fing][0:len(tasks[fing])-3]
                else :
                    tasks[fing] = tasks[fing]+'(!)'
        elif cmd[0]=="`" :
            try:
                fing=int(cmd[1:])
            except ValueError:
                fing=cmd[1:]
            else:
                try:
                    fing=tasks[fing]
                except:
                    fing=cmd[1:]
            finally:
                if fing[:5]=='[WEB]':
                    web_open(fing)
                else:
                    do('start http://www.google.com/search?q='+fing.replace(' ','+'))
                
        elif cmd[0]=="'" :
            tasks.append(cmd[1:])                            
        else:
            temp=-1
            for i in web_keywords:
                temp=cmd.lower().find(i)
                if temp>-1:
                    break
            if temp>-1:
                if temp==0:
                    print ">>Grabbing webpage title..."
                    try:
                        urlcontext = urlopen( cmd ).read()
                    except:
                        urltitle='(A currently unaviliable web page)'
                    else:
                        try:
                            urltitle=urlcontext[urlcontext.lower().index('<title>')+7:urlcontext.lower().index('</title>')].replace('\n','')
                        except ValueError:
                            urltitle='(Untitled webpage)'
                        try:
                            urltitle=urltitle.decode('UTF-8').encode('GBK')
                        except :
                            pass
                    finally:
                        tasks.append('[WEB]'+urltitle.strip()+': '+shorten_url(cmd))
                else:
                    tasks.append('[WEB]'+cmd[:temp].strip()+': '+shorten_url(cmd[temp:]))
            else: #open?
                try :
                    fing = int(cmd)
                except ValueError:
                    if cmd not in tasks :
                        tasks.append(cmd)
                else : #open??
                    if fing < len(tasks) : #open!
                        web_open(tasks[fing])
                        fila = open ( 'history.txt', 'a' )
                        fila.write ('['+ctime()+']'+tasks[fing])
                        fila.write ('\n')
                        fila.close()
                        tasks.remove(tasks[fing])
                    else:
                        tasks.append(cmd)
if len(sys.argv)==1:
    do("title LinoTask V0.4  ---------------------   Usage:[`:seach/open /:highlight ':force add] && color 0f")
    while True :
        screen_buffer=''''''
        size()#do('cls')
        for i in range(len(tasks)):
            screen_buffer=screen_buffer+' '+str(i)+' =>\t'+tasks[i]+'\n'
        print screen_buffer
        cmd = raw_input('>')
        if process(cmd)==-1:
            break
        save()
else:
    tmp=''
    for i in sys.argv[1:]:
        tmp=tmp+i+' '
    process(tmp)
    save()
