#!/usr/bin/python
# -*- coding: utf-8 -*-
#####################################################################
#following are imported for working
#####################################################################
import win32com.client
import os


#####################################################################
#This function for word file replace words greater than 255
#####################################################################
def search_replace_all(word_file, find_str, replace_str):
    ''' replace all occurrences of `find_str` w/ `replace_str` in `word_file` '''
    wdFindContinue = 1
    wdReplaceAll = 2
    replace_str_split=""

    # Dispatch() attempts to do a GetObject() before creating a new one.
    # DispatchEx() just creates a new one.
    # expression.Execute(FindText, MatchCase, MatchWholeWord,
    #   MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward,
    #   Wrap, Format, ReplaceWith, Replace)
    total=0
    num=0
    j=0
    i=0
    if len(replace_str)>=255:
        total=len(replace_str)
        if total%245==0:
            num=total/245
        else:
            num=total//245+1
        for i in range(num):
            j=i*244
            if i==0 :
                replace_str_split=replace_str[i:244]+"conti...."
                app.Selection.Find.Execute(find_str, False, False, False, False, False,True, wdFindContinue, True, replace_str_split, wdReplaceAll)
                i=i+1
            elif i==num-1:
                replace_str_split=replace_str[j:j+244]
                app.Selection.Find.Execute("conti....", False, False, False, False, False,True, wdFindContinue, True, replace_str_split, wdReplaceAll)
            else:
                replace_str_split=replace_str[j:j+244]+"conti...."
                app.Selection.Find.Execute("conti....", False, False, False, False, False,True, wdFindContinue, True, replace_str_split, wdReplaceAll)
                i=i+1
    else:
        app.Selection.Find.Execute(find_str, False, False, False, False, False,True, wdFindContinue, True, replace_str, wdReplaceAll)



#####################################################################
#This class easyword.
#Not have test for this function
#####################################################################
class easyWord:
    ''' Some convenience methods for Excel documents accessed through COM. '''
    def __init__(self,visible=False):
        self.wdApp = win32com.client.DispatchEx('Word.Application')
        self.wdApp.Visible = visible
        self.wdApp.DisplayAlerts = False

    def new(self,filename=None):
        ''' Create a new Word document. If 'filename' specified, use the file as a template. '''
        if filename:
            return self.wdApp.Documents.Add(filename)
        else:
            return self.wdApp.Documents.Add()

    def open(self,filename):
        ''' Open an existing Word document for editing. '''
        return self.wdApp.Documents.Open(filename)

    def visible(self,visible=True):
        self.wdApp.Visible = visible

    def find(self,text,MatchWildcards=False):
        ''' Find the string '''
        find = self.wdApp.Selection.Find
        find.ClearFormatting()
        find.Execute(text, False, False, MatchWildcards, False, False, True, 0)
        return self.wdApp.Selection.Text

    def replaceAll(self,oldStr,newStr):
        ''' Find the oldStr and replace with the newStr. '''
        find = self.wdApp.Selection.Find
        find.ClearFormatting()
        find.Replacement.ClearFormatting()
        find.Execute(oldStr, False, False, False, False, False, True, 1, True, newStr, 2)

    def updateToc(self):
        for tocitem in self.wdApp.ActiveDocument.TablesOfContents:
            tocitem.Update()

    def save(self):
        ''' Save the active document '''
        self.wdApp.ActiveDocument.Save()

    def saveAs(self,filename,delete_existing=True):
        ''' Save the active document as a different filename. If 'delete_existing' is specified and the file already exists, it will be deleted before saving. '''
        if delete_existing and os.path.exists(filename):
            os.remove(filename)
        self.wdApp.ActiveDocument.SaveAs(FileName=filename)

    def close(self):
        ''' Close the active workbook. '''
        self.wdApp.ActiveDocument.Close()

    def quit(self):
        ''' Quit Word '''
        return self.wdApp.Quit()


#####################################################################
#This class easyword.
#Not have test for this function
#####################################################################
class easyExcel:
    """A utility to make it easier to get at Excel. Remembering to save the data is your problem, as is error handling. Operates on one workbook at a time."""
    def __init__(self, filename=None):
        self.xlApp = win32com.client.DispatchEx('Excel.Application')
        if filename:
            self.filename = filename
            self.xlBook = self.xlApp.Workbooks.Open(filename)
        else:
            self.xlBook = self.xlApp.Workbooks.Add()
            self.filename = ''

    def save(self, newfilename=None):
        if newfilename:
            self.filename = newfilename
            self.xlBook.SaveAs(newfilename)
        else:
            self.xlBook.Save()

    def close(self):
        self.xlBook.Close(SaveChanges=0)
        del self.xlApp

    def getCell(self, sheet, row, col):
        "Get value of one cell"
        sht = self.xlBook.Worksheets(sheet)
        return sht.Cells(row, col).Value

    def setCell(self, sheet, row, col, value):
        "set value of one cell"
        sht = self.xlBook.Worksheets(sheet)
        sht.Cells(row, col).Value = value

    def getRange(self, sheet, row1, col1, row2, col2):
        "return a 2d array (i.e. tuple of tuples)"
        sht = self.xlBook.Worksheets(sheet)
        return sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2)).Value

    def addPicture(self, sheet, pictureName, Left, Top, Width, Height):
        "Insert a picture in sheet"
        sht = self.xlBook.Worksheets(sheet)
        sht.Shapes.AddPicture(pictureName, 1, 1, Left, Top, Width, Height)

    def cpSheet(self, before):
        "copy sheet"
        shts = self.xlBook.Worksheets
        shts(1).Copy(None,shts(1))


















