// Written by google AI: please write a java script to draw a 2x2 table to a powerpoint file using apache poi
import org.apache.poi.xslf.usermodel.*;
import java.awt.geom.Rectangle2D;
import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.sl.usermodel.TableCell.BorderEdge;

public class MergedCellBorderProblem {
    public static void main(String[] args) throws IOException {
        // 1. Create a new PPTX slideshow
        try (XMLSlideShow ppt = new XMLSlideShow()) {
            XSLFSlide slide = ppt.createSlide();

            // 2. Create a table
            int numRows = 5;
            int numCols = 3;
            XSLFTable table = slide.createTable(numRows, numCols);

            // 3. Position and Size the table
            table.setAnchor(new Rectangle2D.Double(100, 100, 300, 100));

            // 4. Set Cell Content and Basic Formatting
            for (int r = 0; r < numRows; r++) {
                for (int c = 0; c < numCols; c++) {
                    XSLFTableCell cell = table.getCell(r, c);
                    XSLFTextParagraph p = cell.addNewTextParagraph();
                    XSLFTextRun r1 = p.addNewTextRun();
                    r1.setText("r" + r + " c" + c);
                }
            }

            // Merge all 3 cells in row 0
            table.mergeCells(0, 0, 0, 2);
            applyBorder(table.getCell(0,0), java.awt.Color.RED);
            // Merge cells in col 1 rows 2-4
            table.mergeCells(2, 4, 1, 1);
            applyBorder(table.getCell(2,1), java.awt.Color.BLUE);
            
            // 5. Save the file
            try (FileOutputStream out = new FileOutputStream("MergedCellBorderProblem.pptx")) {
                ppt.write(out);
                System.out.println("Table created successfully: MergedCellBorderProblem.pptx");
            }
        }
    }

    private static void applyBorder(XSLFTableCell cell, Color color) {
        double borderWidth = 2.0; // Border thickness

        // Apply borders to all four sides of the cell
        cell.setBorderColor(BorderEdge.top, color);
        cell.setBorderColor(BorderEdge.bottom, color);
        cell.setBorderColor(BorderEdge.left, color);
        cell.setBorderColor(BorderEdge.right, color);

        cell.setBorderWidth(BorderEdge.top, borderWidth);
        cell.setBorderWidth(BorderEdge.bottom, borderWidth);
        cell.setBorderWidth(BorderEdge.left, borderWidth);
        cell.setBorderWidth(BorderEdge.right, borderWidth);
    }
}