/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mytime.gui.controller;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXDialog;
import com.jfoenix.controls.JFXDialogLayout;
import com.jfoenix.controls.JFXSpinner;
import java.io.File;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import mytime.be.Group;
import mytime.be.Guild;
import mytime.be.Person;
import mytime.gui.model.ManagerModel;
import mytime.gui.model.Model;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.controlsfx.control.spreadsheet.GridBase;
import org.controlsfx.control.spreadsheet.SpreadsheetCell;
import org.controlsfx.control.spreadsheet.SpreadsheetCellType;
import org.controlsfx.control.spreadsheet.SpreadsheetView;
/**
* FXML Controller class
*
* @author Stefan Olsen
*/
public class ManagerDocumentationViewController implements Initializable
{
@FXML
private SpreadsheetView spreadSheetView;
@FXML
private BorderPane borderPane;
private ManagerModel mgrModel;
private GridBase grid;
private HashMap<Integer, Person> cellToPersonMap;
private HashMap<Integer, Group> cellToGroupMap;
private AtomicInteger row, column;
private JFXDialog dialog;
private Timer timer;
private TimerTask timerTask;
@FXML
private StackPane stackPane;
@FXML
private JFXButton btnLoad;
@FXML
private JFXButton btnExport;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb)
{
initDialogLayout();
mgrModel = ManagerModel.getInstance();
cellToPersonMap = new HashMap<>();
cellToGroupMap = new HashMap<>();
row = new AtomicInteger(1);
column = new AtomicInteger(1);
setBtnIcons();
}
/**
* Sets the icons on the buttons.
*/
private void setBtnIcons()
{
ImageView export = new ImageView(new Image("/mytime/gui/view/css/excel_icon.png"));
ImageView load = new ImageView(new Image("/mytime/gui/view/css/charging.png"));
btnLoad.setGraphic(load);
btnExport.setGraphic(export);
}
/**
* dialog layout
*/
private void initDialogLayout()
{
Label lblDialogMessage = new Label();
lblDialogMessage.setText("Henter data, dette kan tage lidt tid...");
lblDialogMessage.setGraphic(new JFXSpinner());
// lblDialogMessage.getStyleClass().add("lblDialogMessage");
JFXDialogLayout layout = new JFXDialogLayout();
layout.getChildren().add(lblDialogMessage);
dialog = new JFXDialog(stackPane, layout, JFXDialog.DialogTransition.CENTER);
// dialog.setOnDialogClosed(e
// ->
// {
// timer.cancel();
// });
// dialog.setOnDialogOpened(e
// ->
// {
// timer = new Timer(true);
// timerTask = new TimerTask()
// {
// @Override
// public void run()
// {
//
// dialog.close();
//
// }
// };
//
// timer.schedule(timerTask, 1200);
// });
}
/**
* Loads all groups and persons.
*/
private void loadDataInSpreadSheet()
{
spreadSheetView.setEditable(false);
List<Person> allPersons = Collections.synchronizedList(new ArrayList<>());
List<Node> allPersonNodes = mgrModel.getAllPersonNodes();
allPersonNodes.stream().parallel().forEach(personNode
->
{
Person p = (Person) personNode.getUserData();
allPersons.add(p);
});
//Get all the guilds
List<Group> allGroups = new ArrayList<>(mgrModel.getAllGroups());
//Added some dummy groups, becourse SpreadSheetView is kinda fucked up, and i'm too dumb to understand its documentation.
allGroups.add(new Guild("TIMER I ALT:", 0, 0, "", ""));
allGroups.add(new Guild("SIDST AKTIV:", 0, 0, "", ""));
// allGroups.add(new Guild("SIDST AKTIV:", 0, 0, "", ""));
//nedad
int rowCount = allPersons.size();
//henad
int columnCount = allGroups.size();
grid = new GridBase(rowCount, columnCount);
ObservableList<ObservableList<SpreadsheetCell>> rows = FXCollections.observableArrayList();
for (int row = 0; row < grid.getRowCount(); ++row)
{
int currentColumn = 0;
Person currentPerson = allPersons.get(row);
ObservableList<SpreadsheetCell> rowForOnePerson = FXCollections.observableArrayList();
if (row == 0)
{
SpreadsheetCell cell = SpreadsheetCellType.STRING.createCell(row, currentColumn, 1, 1, "Laug:");
cell.setStyle("-fx-font-weight: bold");
rowForOnePerson.add(cell);
} else
{
SpreadsheetCell cell = SpreadsheetCellType.STRING.createCell(row, currentColumn, 1, 1, currentPerson.getFullName());
cellToPersonMap.put(row, currentPerson);
rowForOnePerson.add(cell);
for (int i = 1; i < columnCount + 1; i++)
{
rowForOnePerson.add(SpreadsheetCellType.STRING.createCell(row, i, 1, 1, ""));
}
}
for (int column = 1; column < columnCount + 1; ++column)
{
Group group = allGroups.get(column - 1);
SpreadsheetCell cell = SpreadsheetCellType.STRING.createCell(0, column, 1, 1, group.getName().get());
cell.setStyle("-fx-font-weight: bold");
// cell.
cellToGroupMap.put(column, group);
rowForOnePerson.add(cell);
}
rows.add(rowForOnePerson);
}
grid.setRows(rows);
spreadSheetView.setGrid(grid);
}
/**
* On action when you press load.
*
* @param event
*/
@FXML
private void handleLoadData(ActionEvent event)
{
loadDataInSpreadSheet();
populateSpreadSheet();
}
/**
* Inserts all hour transactions into the sheet.
*/
private void populateSpreadSheet()
{
dialog.show();
ExecutorService svc = Executors.newFixedThreadPool(4, (Runnable r)
->
{
Thread t = Executors.defaultThreadFactory().newThread(r);
t.setDaemon(true);
return t;
});
Runnable go = new Runnable()
{
@Override
public void run()
{
ExecutorService threadPool = Executors.newFixedThreadPool(grid.getRowCount(), (Runnable r)
->
{
Thread t = Executors.defaultThreadFactory().newThread(r);
t.setDaemon(true);
return t;
});
//minus the two last rows for sub total and last active.
int totalColumns = grid.getColumnCount() - 2;
// submit jobs to be executing by the pool
for (int i = 0; i < grid.getRowCount(); i++)
{
Person currentPerson = cellToPersonMap.get(i);
final int ii = i;
threadPool.submit(new Runnable()
{
public void run()
{
try
{ //
int[][] arrayOfHours = Model.getInstance().getHoursWorkedInEachGuildOnByPerson(currentPerson, -1);
for (int j = 1; j < totalColumns; j++)
{
final Integer jFinal = j;
Platform.runLater(()
->
{
grid.setCellValue(ii, jFinal, arrayOfHours[jFinal-1][1]);
});
// try
// {
//Group currentGroup = cellToGroupMap.get(j);
//int hoursWorkedOnGuild = mgrModel.getHoursWorkedOnOneGuildByVolunteer(currentPerson.getId().get(), currentGroup.getId().get());
// final Integer jFinal = j;
//
//
// System.out.println("Set cell:(" + ii + "," + j + ") to: " + hoursWorkedOnGuild + "for person:" + currentPerson.getFullName() + " In group: " + currentGroup.getName().get());
// } catch (SQLException ex)
// {
// ex.printStackTrace();
// }
}
} catch (SQLException ex)
{
Logger.getLogger(ManagerDocumentationViewController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// once you've submitted your last job to the service it should be shut down
threadPool.shutdown();
try
{
// wait for the threads to finish if necessary
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
Platform.runLater(()
->
{
dialog.close();
calcTotalHours();
});
} catch (InterruptedException ex)
{
Logger.getLogger(ManagerDocumentationViewController.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
svc.execute(go);
}
/**
* Calculates total documented hours from the data in the spreadsheet.
*/
private void calcTotalHours()
{
int totalHourscolumn = grid.getColumnCount() - 2;
int startRowIdx = 1;
ObservableList<ObservableList<SpreadsheetCell>> rows = grid.getRows();
for (int j = 1; j < rows.size(); j++)
{
ObservableList<SpreadsheetCell> row1 = rows.get(j);
int totHoursForOnePerson = 0;
for (int i = 1; i < totalHourscolumn; i++)
{
totHoursForOnePerson += Integer.parseInt(row1.get(i).getText());
}
grid.setCellValue(j, totalHourscolumn, totHoursForOnePerson + " timer");
}
}
@FXML
private void handleExportSpreadSheet(ActionEvent event)
{
handleExportToXls();
}
/**
* Creates a Excel document from the spreadsheet in the GUI.
*/
private void handleExportToXls()
{
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Microsoft Excel files (*.xls)", "*.xls");
fileChooser.getExtensionFilters().add(extFilter);
File selectedFile = fileChooser.showSaveDialog(null);
if (selectedFile != null)
{
mgrModel.saveXlsDocument(generateXlsDocument(), selectedFile);
}
// To write out the workbook into a file we need to create an output
// stream where the workbook content will be written to.
}
private HSSFWorkbook generateXlsDocument()
{
HSSFWorkbook workbook = new HSSFWorkbook();
// Create two sheets in the excel document and name it First Sheet and
// Second Sheet.
HSSFSheet firstSheet = workbook.createSheet("Time dokumentering");
// Manipulate the firs sheet by creating an HSSFRow which represent a
// single row in excel sheet, the first row started from 0 index. After
// the row is created we create a HSSFCell in this first cell of the row
// and set the cell value with an instance of HSSFRichTextString
// containing the words FIRST SHEET.
ObservableList<ObservableList<SpreadsheetCell>> rows = grid.getRows();
int totalColumns = grid.getColumnCount();
for (int j = 0; j < rows.size(); j++)
{
ObservableList<SpreadsheetCell> row1 = rows.get(j);
HSSFRow rowToAdd = firstSheet.createRow(j);
for (int i = 0; i < totalColumns; i++)
{
HSSFCell cellA = rowToAdd.createCell(i);
String text = row1.get(i).getText();
if (j == 0 || i == 0 || i == totalColumns-1 || text.contains("timer"))
{
cellA.setCellValue(new HSSFRichTextString(row1.get(i).getText()));
} else
{
cellA.setCellValue(new HSSFRichTextString(row1.get(i).getText() + " t"));
}
}
}
return workbook;
}
}