package controller.export;

import controller.Controller;
import controller.history.Application_Controller;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.sig.fw.db.bddc.model.Society;
import org.sig.fw.db.corrida.dao.Facture_DBAO;
import org.sig.fw.db.corrida.dao.Rfp_DBAO;
import org.sig.fw.db.corrida.model.Facture;
import org.sig.fw.db.corrida.model.Rfp;
import org.sig.fw.layout.contener.SInternalFrame;
import org.sig.fw.layout.pane.SOptionPane;
import org.sig.fw.spdf.common.FileTools;
import org.sig.fw.spdf.common.PDF;
import org.sig.fw.utility.date.SDate;
import pdf.Facture_PDF;
import view.export.Export_Month_Facture_View;

import java.awt.*;
import java.io.*;
import java.util.List;

public class Export_Month_Facture_Controller extends Controller
{
	private Export_Month_Facture_View vw_export_month_facture = null;
	
	public Export_Month_Facture_Controller(Application_Controller ctrl_application)
	{
		super(ctrl_application);
		
		
		this.vw_export_month_facture = new Export_Month_Facture_View(this);
		this.vw_export_month_facture.setVisible(true);
	}
	
	public SInternalFrame getView()
	{
		return this.vw_export_month_facture;
	}
	
	public void startProcess(Society society, String type, String format, SDate date, String url)
	{
		new Thread(new Runnable()
		{
			
			@Override
			public void run() 
			{
				vw_export_month_facture.setProgressValue("Vérification des données", 0);
				if(format.equals("PDF")) {
					exportPDF(society, type, date, url);
					vw_export_month_facture.setProgressValue("Ouverture du fichier", 100);
					vw_export_month_facture.stopProcess("");
					return;
				}
				if(url.isEmpty())
				{
					vw_export_month_facture.stopProcess("Le champ 'Fichier' ne peut être vide !");
					return;
				}
				
				File file = new File(url);
				
				if(file.isDirectory())
				{
					vw_export_month_facture.stopProcess("Le 'Fichier' renseigné est un répertoire !");
					return;
				}
				
				if(!file.exists())
				{
					vw_export_month_facture.stopProcess("Le fichier renseigné n'existe pas.");
					return;
				}
				
				vw_export_month_facture.setProgressValue("Récupération des données de la base", 0);
				List<Facture> datas = new Facture_DBAO("fact").getDataForExport(society, type, date);
				
				try 
				{
					InputStream ExcelFileToRead = new FileInputStream(url);
					XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
					XSSFSheet sheet = wb.getSheetAt(0);

					/* Récupération de la dernière ligne sans écriture */
					int row = 1;
					while(true)
					{
						if(sheet.getRow(row) != null)
							row++;
						else
							break;
					}
					
					double progress = 0;
					double delta = 0;
					if(datas.size() != 0)
					{
						delta = 100 / datas.size();
					}

					for(Facture facture : datas)
					{
						XSSFRow excel_row = sheet.createRow(row);

						addStringCell(wb, excel_row, 0, "CORRIDA", 0);
						addStringCell(wb, excel_row, 1, facture.getFactureNumber(), 1);
						addStringCell(wb, excel_row, 2, facture.getFacturedDate().getFormattedDate(SDate.FORMAT_FR), 1);
						addStringCell(wb, excel_row, 3, facture.getCommande().getCc().getBddcClient().getCompany(), 1);
						addStringCell(wb, excel_row, 4, facture.getState().getLongValue(), 1);
						addDoubleCell(wb, excel_row, 5, facture.getAmountHt());
						addDoubleCell(wb, excel_row, 6, facture.getAmountTva());
						addDoubleCell(wb, excel_row, 7, facture.getAmountNet());
						addStringCell(wb, excel_row, 8, facture.getEcheance().getFormattedDate(SDate.FORMAT_FR), 1);
						addStringCell(wb, excel_row, 9, "", 1);
						addStringCell(wb, excel_row, 10, facture.getCommande().getDossier().getReferenceNumber(), 1);
						addStringCell(wb, excel_row, 11, facture.getResponsible().getCode(), 1);
						addStringCell(wb, excel_row, 12, facture.getCategory().getName(), 1);
						addIntegerCell(wb, excel_row, 13, Integer.parseInt(facture.getProductDate().getFormattedDate(SDate.FORMAT_FR).substring(3, 5)));
						addIntegerCell(wb, excel_row, 14, Integer.parseInt(facture.getProductDate().getFormattedDate(SDate.FORMAT_FR).substring(6, 10)));
						addStringCell(wb, excel_row, 15, facture.getCommande().getConstructionSite().getResponsibleParaphe(), 1);
						addStringCell(wb, excel_row, 16, "", 1);
						addStringCell(wb, excel_row, 17, "", 1);
						addStringCell(wb, excel_row, 18, facture.getCommande().getDossier().getLocalisation(), 1);
						addStringCell(wb, excel_row, 19, facture.getCommande().getDossier().getName(), 1);
						List<Rfp> rfps = new Rfp_DBAO("rfp").getWithFacture(facture);
						if(rfps.size() == 2) {
							addStringCell(wb, excel_row, 20, rfps.get(1).getPayer().getBddcClient().getCompany(), 1);
						} else {
							addStringCell(wb, excel_row, 20, "", 1);
						}
						addStringCell(wb, excel_row, 21, facture.getPaymentMode().getShortValue().contains("FACTOR") ? "FACTOR" : "", 1);
						row++;
						progress += delta;
						vw_export_month_facture.setProgressValue("Insertion des données", (int) progress);
					}
					

					wb.write(new FileOutputStream(new File(url)));
					wb.close();
					vw_export_month_facture.setProgressValue("Ouverture du fichier", 100);
					Desktop.getDesktop().open(new File(url));
				} 
				catch (IOException e) 
				{
					vw_export_month_facture.stopProcess("Une erreur est survenu. Veuillez vérifier que le fichier sélectionné est bien un fichier Excel et qu'il n'est pas ouvert.");
				}
				vw_export_month_facture.stopProcess("");
			}
		}).start();
	}
	
	private void exportPDF(Society society, String type, SDate date, String url) {
		String path = FileTools.openDirectory(url);
		if(path.isEmpty()) {
			SOptionPane.showInformationMessage("PDF", "Sauvegarde annulée");
		}
		vw_export_month_facture.setProgressValue("Création des PDF", 0);
		List<Facture> datas = new Facture_DBAO("fact").getDataForExport(society, type, date);
		for(Facture f : datas) {
			Facture_PDF pdf = new Facture_PDF(f);
			try {
				pdf.createDocument();
				PDF.save(pdf.getDocument(), path, f.getFactureNumber(), false);
				pdf.closeDocument();
			} catch (IOException e1) {
				SOptionPane.showErrorMessage("Facture PDF", "Une erreur est survenue pour la facture " + f.getFactureNumber() + " : " + e1.getMessage());
			}
		}
		try {
			Desktop.getDesktop().open(new File(path));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	
	private void addStringCell(XSSFWorkbook wb, XSSFRow row, int column, String value, int type)
	{
		XSSFCell cell = row.createCell(column);
		cell.setCellValue(value);
		CellStyle style = getCellStyle(wb);
		if(type == 0)
		{
			style.setFillForegroundColor(IndexedColors.AQUA.getIndex());
			style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		}
		cell.setCellStyle(style);
	}
	
	private void addDoubleCell(XSSFWorkbook wb, XSSFRow row, int column, double value)
	{
		XSSFCell cell = row.createCell(column);
		cell.setCellValue(value);
		CellStyle style = getCellStyle(wb);
		style.setDataFormat(wb.createDataFormat().getFormat("# ##0.00    "));
		cell.setCellStyle(style);
	}
	
	private void addIntegerCell(XSSFWorkbook wb, XSSFRow row, int column, int value)
	{
		XSSFCell cell = row.createCell(column);
		cell.setCellValue(value);
		CellStyle style = getCellStyle(wb);
		
		cell.setCellStyle(style);
	}
	
	private CellStyle getCellStyle(XSSFWorkbook wb)
	{
		CellStyle style = wb.createCellStyle();
        style.setBorderBottom(BorderStyle.THIN);        
        style.setBorderTop(BorderStyle.THIN);        
        style.setBorderLeft(BorderStyle.THIN);        
        style.setBorderRight(BorderStyle.THIN);  
        return style;
	}
}
