Office.initialize = function (reason) {
    $(document).ready(function () {
        //Office.actions.associate("loadSampleData", loadSampleData);
    });
};

const wordOptions = {
    importTheme: true,
    importStyles: true,
    importParagraphSpacing: true,
    importPageColor: true,
    importChangeTrackingMode: true
}

// Show word file content
function showWordFileContent(base64FormatContent) {
    Word.run(function (context) {
        var document = context.document;
        document.insertFileFromBase64(base64FormatContent, Word.InsertLocation.replace, wordOptions);
        return context.sync();
    }).catch(function (error) {
        console.error('Error:', error);
    });
}

//Clear word file content
function clearWordFileContent() {
    Word.run(async context => {
        context.document.body.clear();

        return context.sync().then(r => {
            const sections = context.document.sections;
            sections.load();

            return context.sync().then(function () {
                sections.items.forEach(function (section) {
                    // Clear the Body
                    section.body.clear();

                    // Clear any Headers
                    section.getHeader("Primary").clear();
                    section.getHeader("FirstPage").clear();
                    section.getHeader("EvenPages").clear();

                    // Clear any Footers
                    section.getFooter("Primary").clear();
                    section.getFooter("FirstPage").clear();
                    section.getFooter("EvenPages").clear();
                });

                //context.document.body.select();

                return context.sync().then(function () {
                    console.log("Clear");
                });
            });
        });
    }).catch(function (error) {
        console.error('Error:', error);
    });
}

//Get word file name
function getDocumentName() {
    return new Promise((resolve, reject) => {
        Office.context.document.getFilePropertiesAsync(function (result) {
            if (result.status === Office.AsyncResultStatus.Succeeded) {
                var fileInfo = result.value;
                var documentName = fileInfo.url.substring(fileInfo.url.lastIndexOf('\\') + 1);
                resolve(documentName);
            } else {
                reject(result.error.message);
            }
        });
    });
}

//Get word file content
function getDocumentAsCompressed() {
    return new Promise((resolve, reject) => {
        Office.context.document.getFileAsync(Office.FileType.Compressed, { sliceSize: 65536 /*64 KB*/ },
            function (result) {
                if (result.status == "succeeded") {
                    const myFile = result.value;
                    const sliceCount = myFile.sliceCount;
                    const docDataSlices = [];
                    let slicesReceived = 0, gotAllSlices = true;

                    getSliceAsync(myFile, 0, sliceCount, gotAllSlices, docDataSlices, slicesReceived)
                        .then(docDataSlices => {
                            let docData = [];
                            for (let i = 0; i < docDataSlices.length; i++) {
                                docData = docData.concat(docDataSlices[i]);
                            }

                            let fileContent = '';
                            for (let j = 0; j < docData.length; j++) {
                                fileContent += String.fromCharCode(docData[j]);
                            }

                            const base64Content = window.btoa(fileContent);
                            resolve(base64Content);
                        })
                        .catch(error => reject(error));
                } else {
                    reject(result.error.message);
                }
            });
    });
}

function getSliceAsync(file, nextSlice, sliceCount, gotAllSlices, docDataSlices, slicesReceived) {
    return new Promise((resolve, reject) => {
        file.getSliceAsync(nextSlice, function (sliceResult) {
            if (sliceResult.status == "succeeded") {
                if (!gotAllSlices) {
                    return;
                }

                docDataSlices[sliceResult.value.index] = sliceResult.value.data;
                if (++slicesReceived == sliceCount) {
                    file.closeAsync();
                    resolve(docDataSlices);
                }
                else {
                    getSliceAsync(file, ++nextSlice, sliceCount, gotAllSlices, docDataSlices, slicesReceived)
                        .then(resolve)
                        .catch(reject);
                }
            }
            else {
                gotAllSlices = false;
                file.closeAsync();
                reject(sliceResult.error.message);
            }
        });
    });
}

function setItemInPoaLocalStorage(key, value) {
    if (typeof (Storage) !== "undefined") {
        localStorage.setItem(key, value);
    } else {
        console.error("Error while setting item in local storage.");
    }
}

function getItemFromPoaLocalStorage(key) {
    if (typeof (Storage) !== "undefined") {
        return localStorage.getItem(key);
    } else {
        console.error("Error while getting item from local storage.");
        return null;
    }
}

function removeItemFromPoaLocalStorage(key) {
    if (typeof (Storage) !== "undefined") {
        localStorage.removeItem(key);
    } else {
        console.error("Error while removing item from local storage.");
    }
}