import os
from docx import Document
from docx.shared import Inches

def buildDocument(path,filename):
    '''
    instrucions : build a document writer
    :param path:
    :param filename:
    :return:
    '''
    if filename[-3:]!='doc':
        if filename[-4:] !='docx':
            raise ValueError('{} is not a word file'.format(filename))
    if os.path.exists(os.path.join(path,filename)):
        return Document(os.path.join(path,filename))
    return Document()

def saveDocument(document,path,filename):
    if filename[-3:] != 'doc':
        if filename[-4:] != 'docx':
            raise ValueError('{} is not a word file'.format(filename))
    return document.save(os.path.join(path,filename))

def insert_table(document,df):
    '''
    instructions : plot table which insert into docx
    :param document: document obj
    :param df: dataframe
    :return:
    '''

    cols = df.columns
    values = df.values
    table = document.add_table(rows=1, cols=len(cols),style='Medium Grid 1 Accent 1')
    hdr_cells = table.rows[0].cells
    for i in range(len(cols)):
        hdr_cells[i].text = cols[i]
    for value in values:
        row_cells = table.add_row().cells
        for i in range(len(cols)):
            if type(value[i])==str:
                row_cells[i].text = value[i]
            else:
                row_cells[i].text = str(value[i])
    return document
