package ru.javastudy.spring.mvc;


import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;
import ru.javastudy.spring.cats.Cat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

public class ExcelView extends AbstractExcelView{

    @Override
    protected void buildExcelDocument(Map model, HSSFWorkbook workbook,
                                      HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        HSSFSheet excelSheet = workbook.createSheet("Cats List");
        setExcelHeader(excelSheet);

        List<Cat> cats = (List<Cat>) model.get("catsList");
        setExcelRows(excelSheet, cats);

    }

    public void setExcelHeader(HSSFSheet excelSheet) {
        HSSFRow excelHeader = excelSheet.createRow(0);
        excelHeader.createCell(0).setCellValue("Name");
        excelHeader.createCell(1).setCellValue("Breed");
        excelHeader.createCell(2).setCellValue("Weight");
        excelHeader.createCell(3).setCellValue("Birthday");
    }

    public void setExcelRows(HSSFSheet excelSheet, List<Cat> cats){
        int record = 1;
        for (Cat cat : cats) {
            HSSFRow excelRow = excelSheet.createRow(record++);
            excelRow.createCell(0).setCellValue(cat.getName());
            excelRow.createCell(1).setCellValue(cat.getBreed());
            excelRow.createCell(2).setCellValue(cat.getWeight());
            excelRow.createCell(3).setCellValue(cat.getBirthday());
        }
    }
}
