#-*- coding: utf-8 -*-
#JAVA_class v0.9 :plugin for MobilHex by fann95
class EXTENSION:
    def __init__(s,DATA,EXT):
        s.EXT=EXT#object
        #s.EXT.note("Hello")
        #s.EXT.progress(i,len(cycle))
        s.DATA=DATA#data is read from a file
        s.STRINGS=[]#found strings in unicode(s.STRINGS=[[string,color],[..,.],..])
        s.INDEX=[]#addresses beginning of text lines
        #reserved name in mobilhex (EXTENSION,SEARCH_STRINGS,EDIT_DATA,DATA,STRINGS,INDEX)

    def SEARCH_STRINGS(s):#algorithm for finding(nothing returning but fills a s.STRINGS and s.INDEX) 
        i=0
        while i<len(s.DATA)-1:
            s.EXT.progress(i,len(s.DATA)-1)
            i=s.DATA.find("\x01\x00",i)
            if i==-1:
                break
            end=i+3+eval("0x"+s.DATA[i+2].encode("hex"))
            if end<len(s.DATA):
                if len(s.DATA[i+3:end])<=1 or (s.DATA[i+3:end].find("\x01\x01")!=-1) or (s.DATA[i+3:end].find("\x07")!=-1) or\
                   (s.DATA[i+3:end].find("\x00\x00")!=-1) or (s.DATA[i+3:end].find("\x01\x00")!=-1):
                    i+=2;continue
                else:
                    Result=s.DATA[i+3:end]
                    try:
                        Result.decode("ascii")
                        color=0xffffff
                    except:color=0xff0000
                    try:
                        s.STRINGS.append([Result.decode("utf-8"),color])
                        s.INDEX.append(i+3)
                    except:
                        i+=2;continue
                    i=end;continue
            else:break
        if s.STRINGS==[]:s.EXT.note("không tìm thấy")

    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]-1]+chr(len(NEW_STRING))+NEW_STRING+s.DATA[s.INDEX[POS]+len(s.STRINGS[POS][0].encode("utf-8")):]
        s.STRINGS[POS][0]=NEW_STRING.decode("utf-8")#update
        c=POS+1
        while c<len(s.INDEX):#update
            s.INDEX[c]=s.INDEX[c]+LL
            c+=1;continue
