#!/usr/bin/python
#
# Copyright (C) 2011 Spreadtrum Communications Inc.
#


__author__ = 'api.hongliang (Hongliang Xin)'


import sys
import codecs
import pdb
import atom
import gdata.contacts.data
import gdata.contacts.client
sys.stdout = codecs.lookup('GBK')[-1]( sys.stdout)

class GContacts(object):

    def __init__(self, dbg = False):
        self.gd_client = gdata.contacts.client.ContactsClient(source='Spreadtrum-eGo')
        self.entries = []
        self.feed = None
        self.dbg = dbg
           
    def Login(self, email, password):
        try:
            self.gd_client.ClientLogin(email, password, self.gd_client.source)
        except gdata.client.BadAuthentication:
            if self.dbg:
                print 'Invalid user credentials given.'
            return 1
        return 0
        
    def _AddFeedEntry(self,feed):
        if len(feed.entry) == 0:
            return  
        count = len(feed.entry)
        for i in range(0,count):
            self.entries.append(feed.entry[i])
            
    def GetAllContacts(self): 
        self.entries = []     
        feed = self.gd_client.GetContacts()
        count = len(feed.entry)
        if self.dbg:
            print  count 
        self._AddFeedEntry(feed)        
        while feed:      
            next = feed.GetNextLink()
            feed = None
            if next:         
                feed = self.gd_client.GetContacts(uri=next.href)
                count += len(feed.entry)
                if self.dbg: 
                    print  count 
                self._AddFeedEntry(feed)                    
                        
        return len(self.entries)
        
    def GetFirstContacts(self):  
        self.entries = []      
        self.feed = self.gd_client.GetContacts()
        count = len(self.feed.entry)
        if self.dbg:
            print  count 
        self._AddFeedEntry(self.feed)
        return count
        
    def GetNextContacts(self):     
        if self.feed is None:
            return 0
        count = 0    
        next = self.feed.GetNextLink()
        self.feed = None
        if next:         
            self.feed = self.gd_client.GetContacts(uri=next.href)
            count = len(self.feed.entry) 
            if self.dbg:
                print  count 
            self._AddFeedEntry(self.feed)
        return count
        
    def GetContact(self,index):
        if index < 0 or index > len(self.entries):
            return ''
                                      
        #entry = self.entries[index]    
        return self.ConvertEntryString(self.entries[index],index)
        
    def FormatTelText(self,str): 
        str = str.upper()    
        str_tmp = str
        format = "0123456789PWN*#+"
        for c in str_tmp:
            if not c in format:
                str = str.replace(c,'')
        return str
        
    def ConvertEntryString(self,entry,ctr):
        if not entry:
            return u""
        entry_str = u""
        name_str = u"NAME: ;"
        mobilephone_str = u"TEL(mobile): ;"
        workphone_str = u"TEL(work): ;"
        homephone_str = u"TEL(home): ;"
        faxphone_str = u"TEL(fax): ;"
        email_str = u"EMAIL: ;"
        mobilephoneflag = 0
        workphoneflag = 0
        homephoneflag = 0
        faxflag = 0
        emailflag = 0
        tel_str = u""
       
        if not entry.name is None:
            full_name = entry.name.full_name is None and u" " or entry.name.full_name.text
            given_name = entry.name.given_name is None and u" " or entry.name.given_name.text
            family_name = entry.name.family_name is None and u" " or entry.name.family_name.text
            if full_name == u" ":
                name_str = u'NAME: %s-%s;' % (given_name, family_name)
            else:          
                name_str = u'NAME: %s;' % (full_name)
                
            if self.dbg:
                print u'\n%s %s: %s - %s' % (ctr+1, full_name, given_name, family_name) 
            
        else:
            title = entry.title is None and u" " or entry.title.text                       
            name_str = u'NAME: %s;' % (title)    
            if self.dbg:
                print u'\n%s name(title): %s' % (ctr+1, title)    
    
        # Display the group id which can be used to query the contacts feed.
        # print 'ID: %s' % entry.id.text     

        for phone_number in entry.phone_number:  
            # mobile phone 
            tel_str = phone_number.text
            tel_str = self.FormatTelText(tel_str)   
            if(phone_number.rel == gdata.data.MOBILE_REL):                
                mobilephoneflag = 1                                
                mobilephone_str = u'TEL(mobile): %s;' % tel_str
                if self.dbg:
                    print u'TEL(mobile): %s' % tel_str 
                    
            elif(mobilephoneflag == 0 and phone_number.rel == gdata.data.WORK_MOBILE_REL):
                mobilephoneflag = 1                               
                mobilephone_str = u'TEL(mobile): %s;' % tel_str
                if self.dbg:
                    print u'TEL(mobile): %s' % tel_str
                     
            # work phone              
            elif(phone_number.rel == gdata.data.WORK_REL):
                workphoneflag = 1                               
                workphone_str = u'TEL(work): %s;' % tel_str
                if self.dbg:
                    print u'TEL(work): %s' % tel_str 
            # home phone                   
            elif(phone_number.rel == gdata.data.HOME_REL):
                homephoneflag = 1                               
                homephone_str = u'TEL(home): %s;' % tel_str 
                if self.dbg:
                    print u'TEL(home): %s' % tel_str 
            # fax   
            elif(phone_number.rel == gdata.data.WORK_FAX_REL):
                faxflag = 1                               
                faxphone_str = u'TEL(fax): %s;' % tel_str
                if self.dbg:
                    print u'TEL(fax): %s' % tel_str  
                    
            elif(faxflag == 0 and phone_number.rel == gdata.data.OTHER_FAX_REL):
                faxflag = 1                               
                faxphone_str = u'TEL(fax): %s;' % tel_str  
                if self.dbg:
                    print u'TEL(fax): %s' % tel_str   
                    
            elif(faxflag == 0 and phone_number.rel == gdata.data.HOME_FAX_REL):
                faxflag = 1                               
                faxphone_str = u'TEL(fax): %s;' % tel_str 
                if self.dbg:
                    print u'TEL(fax): %s' % tel_str 
                    
            elif(faxflag == 0 and phone_number.rel == gdata.data.FAX_REL):
                faxflag = 1                                
                faxphone_str = u'TEL(fax): %s;' % tel_str
                if self.dbg:
                    print u'TEL(fax): %s' % tel_str                     
            else:
                if( mobilephoneflag == 0): 
                    mobilephoneflag = 1
                    mobilephone_str = u'TEL(mobile): %s;' % tel_str 
                    if self.dbg:
                        print u'TEL(mobile): %s' % tel_str    
                elif( workphoneflag == 0):  
                    workphoneflag = 1                                     
                    workphone_str = u'TEL(work): %s;' % tel_str
                    if self.dbg:
                        print u'TEL(mobile): %s' % tel_str 
                elif( homephoneflag == 0):  
                    homephoneflag = 1
                    homephone_str = u'TEL(home): %s;' % tel_str 
                    if self.dbg:
                        print u'TEL(home): %s' % tel_str 
            
        for email in entry.email:
            if email.primary == 'true':                               
                email_str = u'EMAIL: %s;' % (email.address)
                if self.dbg:
                        print u'EMAIL(primary): %s' % (email.address) 
                break
            else:                              
                email_str = u'EMAIL: %s;' % (email.address)
                if self.dbg:
                       print u'Email: %s' % (email.address)  
        
        entry_str = u"" + name_str + mobilephone_str + workphone_str + homephone_str + faxphone_str + email_str
        
        return entry_str
        
    def UpdateContact(self,index,fullname,mobilephone,workphone,homephone,fax,email):
        if index < 0 or index > len(self.entries):
            return 1
        entry = self.entries[index]        
        entry.name.full_name = gdata.data.FullName(text=fullname)
        mobilephoneflag = 0
        workphoneflag = 0
        homephoneflag = 0
        faxflag = 0
        emailflag = 0
        flag = 'true'
        
        for phone_number in entry.phone_number: 
            if(phone_number.primary == 'true'):
                flag = 'false'            
            if(phone_number.rel == gdata.data.MOBILE_REL):
                phone_number.text = mobilephone
                mobilephoneflag = 1             
            elif(phone_number.rel == gdata.data.WORK_REL):
                phone_number.text = workphone
                workphoneflag = 1                     
            elif(phone_number.rel == gdata.data.HOME_REL):
                phone_number.text = homephone
                homephoneflag = 1                
            elif(phone_number.rel == gdata.data.WORK_FAX_REL):
                phone_number.text = fax
                faxflag = 1 
                             
        if(mobilephoneflag == 0 and mobilephone != u""):
            entry.phone_number.append(gdata.data.PhoneNumber(text=mobilephone, 
                primary=flag, rel=gdata.data.MOBILE_REL))
            flag = 'false'
        if(workphoneflag == 0 and workphone != u""):
            entry.phone_number.append(gdata.data.PhoneNumber(text=workphone, 
                primary=flag, rel=gdata.data.WORK_REL))
            flag = 'false'
        if(homephoneflag == 0 and homephone != u""):
            entry.phone_number.append(gdata.data.PhoneNumber(text=homephone, 
                primary=flag, rel=gdata.data.HOME_REL))
            flag = 'false'
        if(faxflag == 0 and fax != u""):
            entry.phone_number.append(gdata.data.PhoneNumber(text=fax, 
                primary=flag, rel=gdata.data.WORK_FAX_REL)) 
                      
        for email in entry.email:            
            if email.primary == 'true':
                email.addr = email
                emailflag = 1
        if(emailflag == 0 and email != u""):
            entry.email.append(gdata.data.Email(address=email, 
                primary='true', rel=gdata.data.WORK_REL))         
                     
        self.gd_client.Update(entry)
        return 0
        
    def AddContact(self,fullname,mobilephone,workphone,homephone,fax,email):    
        new_contact = gdata.contacts.data.ContactEntry(name=gdata.data.Name(full_name=gdata.data.FullName(text=fullname)))
        flag = 'true'
        if (mobilephone != u""):
            new_contact.phone_number.append(gdata.data.PhoneNumber(text=mobilephone, 
                primary=flag, rel=gdata.data.MOBILE_REL))
            flag = 'false'
        if (workphone != u""):
            new_contact.phone_number.append(gdata.data.PhoneNumber(text=workphone, 
                primary=flag, rel=gdata.data.WORK_REL))
            flag = 'false'
        if (homephone != u""):
            new_contact.phone_number.append(gdata.data.PhoneNumber(text=homephone, 
                primary=flag, rel=gdata.data.HOME_REL))
            flag = 'false'
        if (fax != u""):
            new_contact.phone_number.append(gdata.data.PhoneNumber(text=fax, 
                primary=flag, rel=gdata.data.WORK_FAX_REL))
                
        # Create a work email address for the contact and use as primary.         
        if (email != u""):
            new_contact.email.append(gdata.data.Email(address=email, 
                primary='true', rel=gdata.data.WORK_REL))
       
        entry = self.gd_client.CreateContact(new_contact)
    
        if entry:
            if self.dbg:                       
                print 'Creation successful!'
                print 'ID for the new contact:', entry.id.text
            return 0
        else:
            if self.dbg:
                print 'Upload error.'
            return 1
          
        
    def DeleteContact(self,index):
        if index < 0 or index > len(self.entries):
            return 1
        entry = self.entries[index] 
        self.gd_client.Delete(entry)
        return 0
        

gcobj = GContacts(True)

def Login(email,password):
    return gcobj.Login(email,password)
    
def GetAllContacts():
    return gcobj.GetAllContacts()
    
def GetFirstContacts():
    return gcobj.GetFirstContacts()
    
def GetNextContacts():
    return gcobj.GetNextContacts()
    
def GetContact(index):
    return gcobj.GetContact(index)
    
def AddContact(fullname,mobilephone,workphone,homephone,fax,email):
    return gcobj.AddContact(fullname,mobilephone,workphone,homephone,fax,email)
    
def UpdateContact(index,fullname,mobilephone,workphone,homephone,fax,email):
    return gcobj.UpdateContact(index,fullname,mobilephone,workphone,homephone,fax,email)

def DeleteContact(index):
    return gcobj.DeleteContact(index)

if __name__ == '__main__':
    #pdb.set_trace()
    print "login..."
    ret_value = Login('xxxx@gmail.com','xxxx')
    if( ret_value == 0):    
        print "login success"
    else:
        print "login failed"
        exit(0)
    
    #cnum =  GetAllContacts()
    cnum = 0
    count = GetFirstContacts()
    cnum += count
    while count > 0:
        count = GetNextContacts()
        cnum += count
    
    print "there are (%s) contacts" % cnum

    for i in range(0,cnum):
        print GetContact(i)
      
    #for i in range(3,10):
    #    print DeleteContact(i)  
    
        
    print "\n"
    
    #UpdateContact(0,u"Petter",u"44444",u"55555",u"66666",u"777777",u"Petter@sohu.com")
    
    #AddContact(u"Polo Jiang",u"88888888",u"99999999",u"222222",u"99000000",u"Polo.jiang@sohu.com")
    
    
    exit(0)
