package info.bukova.isspst.sort;

import info.bukova.isspst.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.zkoss.zk.au.AuRequest;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.*;
import org.zkoss.zul.*;

import java.io.ByteArrayOutputStream;
import java.util.List;

@SuppressWarnings("serial")
public class CzechSortListheader extends Listheader {
	static {
		addClientEvent(CzechSortListheader.class, Events.ON_RIGHT_CLICK, CE_IMPORTANT | CE_NON_DEFERRABLE);
	}

	public void onRightClick() {
		Menupopup popup = new Menupopup();
		popup.setPage(this.getPage());
		popup.setWidth("250px");
		this.setContext(popup);

		Menuitem item = new Menuitem();
		item.setLabel(StringUtils.localize("ExportToExcel"));
		item.setImage("/img/excel-032.png");
		item.setParent(popup);

		item.addEventListener(Events.ON_CLICK, new EventListener() {
			@Override
			public void onEvent(org.zkoss.zk.ui.event.Event event) throws Exception {
				Listbox listBox = getListbox();

				if (listBox != null) {
					HSSFWorkbook workBook = new HSSFWorkbook();
					HSSFSheet workSheet = workBook.createSheet("export");
					int rowNumber = 0;
					Row excelRow = null;
					Cell excelCell = null;

					HSSFCellStyle cellStyle = workBook.createCellStyle();
					HSSFFont defaultFont = cellStyle.getFont(workBook);

					HSSFCellStyle cellStyleNumber = workBook.createCellStyle();
					cellStyleNumber.setAlignment(CellStyle.ALIGN_RIGHT);
					//http://www.roseindia.net/java/poi/setdataformat.shtml
					//HSSFDataFormat dataNumberFormat = workBook.createDataFormat();
					//cellStyleNumber.setDataFormat(dataNumberFormat.getFormat("# ##0,00"));
					cellStyleNumber.setDataFormat((short)4);

					HSSFCellStyle cellStyleDate = workBook.createCellStyle();
					cellStyleDate.setAlignment(CellStyle.ALIGN_RIGHT);
					//http://www.roseindia.net/java/poi/setdataformat.shtml
					HSSFDataFormat dataDateFormat = workBook.createDataFormat();
					cellStyleDate.setDataFormat(dataDateFormat.getFormat("DD. MM. YYYY"));
					//cellStyleDate.setDataFormat((short) 15);

					int totalCols = 0;

					Listhead listHead = listBox.getListhead();

					if (listHead != null) {
						HSSFCellStyle cellStyleHeader = workBook.createCellStyle();
						cellStyleHeader.setAlignment(CellStyle.ALIGN_CENTER);
						HSSFFont font = workBook.createFont();
						font.setFontName(defaultFont.getFontName());
						font.setFontHeightInPoints(defaultFont.getFontHeightInPoints());
						font.setBold(true);
						cellStyleHeader.setFont(font);

						excelRow = workSheet.createRow(rowNumber++);
						List<Listheader> headerList = listHead.getChildren();
						totalCols = headerList.size();

						for (int i = 0; i < totalCols; i++) {
							Listheader listHeader = headerList.get(i);
							String label = listHeader.getLabel();
							excelCell = excelRow.createCell(i);
							excelCell.setCellStyle(cellStyleHeader);
							excelCell.setCellValue(label);
						}
					}

					List<Listitem> itemList = listBox.getItems();

					for (int i = 0; i < itemList.size(); i++) {
						Listitem item = itemList.get(i);
						excelRow = workSheet.createRow(rowNumber++);

						List<Listcell> cellList = item.getChildren();

						for (int k=0; k < cellList.size(); k++) {
							Listcell cell = cellList.get(k);
							String label = cell.getLabel();

							HSSFCellStyle cellStyleActual = cellStyle;
							excelCell = excelRow.createCell(k);

							if (label != null) {
								if (label.isEmpty()) {
									//List<Component> componentList = cell.getChildren();
									Component component = cell.getFirstChild();

									if (component != null) {
										if (component instanceof Textbox) {
											Textbox textBox = (Textbox) component;
											label = textBox.getValue();
										}
										else if (component instanceof Button) {
											Button button = (Button) component;
											label = button.getLabel();
										}
									}
								}

								if (label.matches("^[+-]?[0-9]{1,3}(,?[0-9]{3})*(\\.[0-9]+)?$")) {
									// english number -1,234.56 (change browser language)
									label = label.replace(",", " ");
									label = label.replace(".", ",");
								}

								if (label.matches("^[+-]?[0-9]{1,3}([ \\xA0][0-9]{3})*([,][0-9]+)?$")) {
									// czech number -1 234,56
									cellStyleActual = cellStyleNumber;
								}
								else if (label.matches("[0-9]{1,2}[.][ \\xA0]?[0-9]{1,2}[.][ \\xA0]?[0-9]{4}")) {
									// czech date
									cellStyleActual = cellStyleDate;
								}
							}

							excelCell.setCellStyle(cellStyleActual);
							excelCell.setCellValue(label);
						}
					}

					for (int i = 0; i < totalCols; i++) {
						//int width = workSheet.getColumnWidth(i);
						workSheet.autoSizeColumn(i);
						int width = workSheet.getColumnWidth(i);
						int maxWidth = 8000;

						if (width > maxWidth) {
							workSheet.setColumnWidth(i, maxWidth);
						}
					}

					ByteArrayOutputStream os = new ByteArrayOutputStream();
					workBook.write(os);
					Filedownload.save(os.toByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "temp" + Long.toString(System.nanoTime()) + ".xlsx");
//					//Filedownload.save(tempFile, "application/vnd.ms-excel");
				}
			}
		});
	}

	@Override
	public void service(AuRequest request, boolean everError) {
		super.service(request, everError);
	}

	@Override
	public void setSort(String type) {
		if (type.startsWith("czech"))
		{
			// czech(propertyName)
			String propertyName = type.substring("czech(".length(), type.length() - 1);
			this.setSortAscending(new CzechStringComparator(propertyName, true));
			this.setSortDescending(new CzechStringComparator(propertyName, false));
		}
		else
		{
			// auto(propertyName)
			super.setSort(type);
		}
	}
}
