#-*- coding: utf-8 -*-
class EXTENSION:
    def __init__(s,DATA,EXT):
        print "plugin UcwebHomepage"
        print "GREN for screenshoot. Please send me this error"
        print "fann95@starport.com.ua"
        s.EXT=EXT#object
        #s.EXT.note("Hello")
        #s.EXT.progress(i,len(obj))
        s.DATA=DATA#data is read from a file
        s.STRINGS=[]#found strings in unicode(s.STRINGS=[[string,color],[..,.],..])
        s.INDEX=[]#addresses beginning of the strings


    def SEARCH_STRINGS(s):#algorithm for finding
        SEARCH=["\x01\x51\x00","\x40\x50\x00","\xff\x00\x00"]
        color=[0xff0000,0xffffff,0xffff00]
        ind=[]
        for x in xrange(len(SEARCH)):
            i=0
            while i<len(s.DATA)-5:
                i=s.DATA.find(SEARCH[x],i)
                if i==-1:
                    break
                LL=eval("0x"+s.DATA[i+3].encode("hex"))
                if i+3+LL>=len(s.DATA):
                    break
                ind.append([i+3,x])
                i+=3+LL;continue
        ind.sort()
        #print str(ind);raise
        for x in xrange(len(ind)):
            LL=eval("0x"+s.DATA[ind[x][0]].encode("hex"))
            try:
                s.STRINGS.append([s.DATA[ind[x][0]+1:ind[x][0]+LL+1].decode("utf-8"),color[ind[x][1]]])
                s.INDEX.append(ind[x][0])
            except:
                if ind[x][1]!=1:
                    s.STRINGS.append([s.DATA[ind[x][0]+1:ind[x][0]+LL+1].decode("utf-8","ignore"),color[ind[x][1]]])
                    s.INDEX.append(ind[x][0])
                else:
                    new_end=s.DATA[ind[x][0]+1:ind[x][0]+LL+1][-3:].find("\xff")
                    if new_end!=-1:
                       s.STRINGS.append([s.DATA[ind[x][0]+1:ind[x][0]+LL+1-3+new_end].decode("utf-8","ignore"),color[ind[x][1]]])
                       s.INDEX.append(ind[x][0]) 
                    else:
                       s.STRINGS.append([s.DATA[ind[x][0]+1:ind[x][0]+LL+1].decode("utf-8","ignore"),0xccc])
                       s.INDEX.append(ind[x][0]) 
        if s.INDEX==[]:s.EXT.note("Not found")
                



    def EDIT_DATA(s,NEW_STRING,POS):#NEW_STRING string entered by the user,
                                      #POS position of strings in the list
        NEW_STRING=NEW_STRING.encode("utf-8")
        LL=len(NEW_STRING)-len(s.STRINGS[POS][0].encode("utf-8"))
        s.DATA=s.DATA[:s.INDEX[POS]]+chr(len(NEW_STRING))+NEW_STRING+s.DATA[s.INDEX[POS]+len(s.STRINGS[POS][0].encode("utf-8"))+1:]
        s.STRINGS[POS][0]=NEW_STRING.decode("utf-8")
        i=POS+1
        while i<len(s.INDEX):#update
            s.INDEX[i]=s.INDEX[i]+LL
            i+=1;continue
