package com.vantec.screen.service;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.opencsv.CSVWriter;
import com.vantec.screen.entity.Company;
import com.vantec.screen.entity.DocumentHeader;
import com.vantec.screen.entity.DocumentStatus;
import com.vantec.screen.entity.InventoryMaster;
import com.vantec.screen.entity.Part;
import com.vantec.screen.entity.TransactionHistory;
import com.vantec.screen.repository.CompanyRepository;
import com.vantec.screen.repository.DocumentHeaderRepository;
import com.vantec.screen.repository.DocumentStatusRepository;
import com.vantec.screen.repository.InventoryMasterRepository;
import com.vantec.screen.repository.PartRepository;
import com.vantec.screen.repository.TransactionHistoryRepository;





@Service("reportService")
public class ReportServiceImpl implements ReportService{
	
	@Autowired
	PartRepository partMasterRepository;
	
	@Autowired
	InventoryMasterRepository inventoryMasterRepository;
	
	@Autowired
	TransactionHistoryRepository transactionHistoryRepository;
	
	@Autowired
	DocumentHeaderRepository documentHeaderRepository;
	
	@Autowired
	DocumentStatusRepository documentStatusRepository;
	
	
	@Autowired
	CompanyRepository companyRepository;
	
	
	   public String generateParts(Company company, Date prevTime,String  currentTime) throws IOException {

	        String extension = ".csv";
	        String fileName = "PartsMaster_" + currentTime;

	        String returnFileName = company.getInterfaceOutput()+fileName+extension;
	        

			BufferedWriter outputfile = new BufferedWriter(new FileWriter(returnFileName));
	        CSVWriter csvwriter = new CSVWriter(outputfile); 
	        
	        List<Part> parts = partMasterRepository.findAllByOrderByPartNumber();
	        
	        List<String[]> partsBody = new ArrayList<String[]>();
	        String header[] = new String[] {"part_number",
	        		                        "part_description", 
	        		                        "location_type_code" , 
	        		                        "location_sub_type_code",
	        		                        "vendor_reference_code" , 
	        		                        "vendor_name"};
	        partsBody.add(header);
	        for(Part part:parts){
	        	String locationTypeCode = part.getFixedLocationType()==null?null:part.getFixedLocationType().getLocationTypeCode();
	            String locationSubTypeCode = part.getFixedSubType()==null?null:part.getFixedSubType().getLocationSubTypeCode();
	        	String vendorReferenceCode = part.getVendor()==null?null:part.getVendor().getVendorReferenceCode();
	        	String vendorName = part.getVendor()==null?null:part.getVendor().getVendorName();
	        	String array[] = new String[] { 
	        			part.getPartNumber(), 
	        			part.getPartDescription(),
	        			locationTypeCode,
	        			locationSubTypeCode,
	        			vendorReferenceCode,
	        			vendorName};
	        	        partsBody.add(array);
	        }

	        csvwriter.writeAll(partsBody);
			csvwriter.flush();
			csvwriter.close();

	        return returnFileName;

	    }
	   
	   public String generateInventorys(Company company, Date prevTime,String  currentTime) throws IOException {
	        
	        String extension = ".csv";
	        String fileName = "InventoryMaster_" + currentTime;
	        String returnFileName = company.getInterfaceOutput()+fileName+extension;
	        
			BufferedWriter outputfile = new BufferedWriter(new FileWriter(returnFileName));
	        CSVWriter csvwriter = new CSVWriter(outputfile); 
	        
	        List<InventoryMaster> inventorys = inventoryMasterRepository.findAll();
	        
	        List<String[]> inventorysBody = new ArrayList<String[]>();
	        String header[] = new String[] {"part_number", 
	        		                        "serial_reference", 
	        		                        "location_code" , 
	        		                        "inventory_qty",
	        		                        "allocated_qty" , 
	        		                        "inventory_status_code",
	        		                        "tag_reference",
	        		                        "stock_date"};
	        inventorysBody.add(header);
	        for(InventoryMaster inventory:inventorys){
	        	String locationCode = inventory.getCurrentLocation()==null?null:inventory.getCurrentLocation().getLocationCode();
	        	String inventoryStatusCode = inventory.getInventoryStatus()==null?null:inventory.getInventoryStatus().getInventoryStatusCode();
	        	String inventoryQty = inventory.getInventoryQty()==null?null:inventory.getInventoryQty().toString();
	        	String allocatedQty = inventory.getAllocatedQty()==null?null:inventory.getAllocatedQty().toString();
	        	String stockDate = inventory.getStockDate()==null?null:inventory.getStockDate().toString();
	        	String array[] = new String[] { 
	        			inventory.getPartNumber(), 
	        			inventory.getSerialReference(),
	        			locationCode,
	        			inventoryQty,
	        			allocatedQty,
	        			inventoryStatusCode,
	        			inventory.getTagReference(),
	        			stockDate};
	        	        inventorysBody.add(array);
	        }

	        csvwriter.writeAll(inventorysBody);
			csvwriter.flush();
			csvwriter.close();
			
	        return returnFileName;

	    }
	   
	   
	   public String generateHistory(Company company, Date prevTime,String  currentTime) throws IOException {
	        
	        String extension = ".csv";
	        String fileName = "CarSetPicks_time_" + currentTime;
	        String returnFileName = company.getInterfaceOutput()+fileName+extension;
	        
			BufferedWriter outputfile = new BufferedWriter(new FileWriter(returnFileName));
	        CSVWriter csvwriter = new CSVWriter(outputfile); 
	        
	        List<TransactionHistory> transactionHistoryList = transactionHistoryRepository.findAllWithShortCodeAndTimeAfter("CSET",prevTime);
	        
	        List<String[]> historyBody = new ArrayList<String[]>();
	        String header[] = new String[] {"id", 
	        		                        "associated_document_reference", 
	        		                        "date_created" , 
	        		                        "from_location_code",
	        		                        "part_number" , 
	        		                        "ran_or_order",
	        		                        "car_set",
	        		                        "serial_reference",
	        		                        "short_code",
	        		                        "txn_qty",
	        		                        "last_updated_by"};
	        historyBody.add(header);
	        for(TransactionHistory transactionHistory:transactionHistoryList){
	        	String array[] = new String[] { 
	        			transactionHistory.getId().toString(), 
	        			transactionHistory.getAssociatedDocumentReference(),
	        			transactionHistory.getDateCreated().toString(),
	        			transactionHistory.getFromLocationCode(),
	        			transactionHistory.getPartNumber(),
	        			transactionHistory.getRanOrOrder(),
	        			transactionHistory.getComment(),
	        			transactionHistory.getSerialReference(),
	        			transactionHistory.getShortCode(),
	        			transactionHistory.getTxnQty().toString(),
	        			transactionHistory.getUpdatedBy()};
	        			historyBody.add(array);
	        }

	        csvwriter.writeAll(historyBody);
			csvwriter.flush();
			csvwriter.close();
			
	        return returnFileName;

	    }
	   
	   
	   public String generateOrders(Company company, Date prevTime,String  currentTime) throws IOException {
		   
	        String extension = ".csv";
	        String fileName = "TA_Completions_time_" + currentTime;
	        String returnFileName = company.getInterfaceOutput()+fileName+extension;
	        
			BufferedWriter outputfile = new BufferedWriter(new FileWriter(returnFileName));
	        CSVWriter csvwriter = new CSVWriter(outputfile); 
	        
	        DocumentStatus status = documentStatusRepository.findByDocumentStatusCode("Picked");
	        

			Date dateUpdated = new Date();
			List<DocumentHeader> docHeaders = documentHeaderRepository.findAllWithBwlvsAndTimeAfter(status ,prevTime);
	        
	        List<String[]> orderHeaders = new ArrayList<String[]>();
	        String header[] = new String[] {"document_reference_code", 
	        		                        "date_completed", 
	        		                        "bwlvs" , 
	        		                        "tanum",
	        		                        "last_updated_by"};
	        orderHeaders.add(header);
	        for(DocumentHeader docHeader:docHeaders){
	        	String array[] = new String[] { 
	        			docHeader.getDocumentReferenceCode(), 
	        			docHeader.getDateUpdated().toString(),
	        			docHeader.getBwlvs(),
	        			docHeader.getTanum(),
	        			docHeader.getUpdatedBy()};
	        	        orderHeaders.add(array);
	        }

	        csvwriter.writeAll(orderHeaders);
			csvwriter.flush();
			csvwriter.close();
			
	        return returnFileName;

	    }
	   
	   
	   public String generateF6Data(Company company, Date runDate,String  currentTime) throws IOException {
	        
	        String extension = ".csv";
	        String fileName = "F6_Transactions_" + currentTime;
	        String returnFileName = company.getInterfaceOutput()+fileName+extension;
	        
			BufferedWriter outputfile = new BufferedWriter(new FileWriter(returnFileName));
	        CSVWriter csvwriter = new CSVWriter(outputfile); 
	        
	        List<TransactionHistory> transactionHistoryList = transactionHistoryRepository.findAllWithShortCodeToLocationCodeAndTimeAfter("CTS",runDate);
	        
	        List<String[]> historyBody = new ArrayList<String[]>();
	        String header[] = new String[] {"id", 
	        		                        "date_created" , 	        		                    
	        		                        "from_location_code",
	        		                        "part_number" , 
	        		                        "last_updated_by",
	        		                        "serial_reference",
	        		                        "short_code",
	        		                        "txn_qty",
	        		                        "to_location_code"};
	        historyBody.add(header);
	        for(TransactionHistory transactionHistory:transactionHistoryList){
	        	String array[] = new String[] { 
	        			transactionHistory.getId().toString(), 
	        			transactionHistory.getDateCreated().toString(),
	        			transactionHistory.getFromLocationCode(),
	        			transactionHistory.getPartNumber(),
	        			transactionHistory.getUpdatedBy(),
	        			transactionHistory.getSerialReference(),
	        			transactionHistory.getShortCode(),
	        			transactionHistory.getTxnQty().toString(),
	        			transactionHistory.getToLocationCode()};
	        			historyBody.add(array);
	        }

	        csvwriter.writeAll(historyBody);
			csvwriter.flush();
			csvwriter.close();
			
	        return returnFileName;

	    }
	   
	   
	   public String generatePim(Company company, Date runDate,String  currentTime) throws IOException {
	        
	        String extension = ".csv";
	        String fileName = "PIM_LPI_time_" + currentTime;
	        String returnFileName = company.getInterfaceOutput()+fileName+extension;
	        
			BufferedWriter outputfile = new BufferedWriter(new FileWriter(returnFileName));
	        CSVWriter csvwriter = new CSVWriter(outputfile); 
	        
	        List<TransactionHistory> transactionHistoryList =  transactionHistoryRepository.findAllPIMLPIShortCodeAndTimeAfter(runDate);
	        
	        List<String[]> historyBody = new ArrayList<String[]>();
	        String header[] = new String[] {"id",
	        		                        "associated_document_reference",
	        		                        "date_created" , 	        		                    
	        		                        "from_location_code",
	        		                        "part_number" , 
	        		                        "ran_or_order" , 
	        		                        "last_updated_by",
	        		                        "serial_reference",
	        		                        "short_code",
	        		                        "txn_qty",
	        		                        "to_location_code"};
	        historyBody.add(header);
	        for(TransactionHistory transactionHistory:transactionHistoryList){
	        	String array[] = new String[] { 
	        			transactionHistory.getId().toString(), 
	        			transactionHistory.getAssociatedDocumentReference(),
	        			transactionHistory.getDateCreated().toString(),
	        			transactionHistory.getFromLocationCode(),
	        			transactionHistory.getPartNumber(),
	        			transactionHistory.getUpdatedBy(),
	        			transactionHistory.getSerialReference(),
	        			transactionHistory.getShortCode(),
	        			transactionHistory.getTxnQty().toString(),
	        			transactionHistory.getToLocationCode()};
	        			historyBody.add(array);
	        }

	        csvwriter.writeAll(historyBody);
			csvwriter.flush();
			csvwriter.close();
			
	        return returnFileName;

	    }
	   
	   public String generateKpStats(Company company, Date runDate,String  currentTime) throws IOException {
	        
	        String extension = ".csv";
	        String fileName = "KPI_Data_time_" + currentTime;
	        String returnFileName = company.getInterfaceOutput()+fileName+extension;
	        
			BufferedWriter outputfile = new BufferedWriter(new FileWriter(returnFileName));
	        CSVWriter csvwriter = new CSVWriter(outputfile); 
	        
	        Calendar cal = Calendar.getInstance();
	        Date today = cal.getTime();

	        cal.add(Calendar.DATE, -1);
	        Date yesterday = cal.getTime();
	        List<DocumentHeader> docHeaders = documentHeaderRepository.findOrderHeaderAndTimeAfter();
	        
	        List<String[]> orderHeaders = new ArrayList<String[]>();
	        String header[] = new String[] {"tanum", 
	        		                        "date_received", 
	        		                        "order_type" , 
	        		                        "expected_delivery",
	        		                        "last_activity_date",
	        		                        "status"};
	        orderHeaders.add(header);
	        for(DocumentHeader docHeader:docHeaders){
	        	String array[] = new String[] { 
	        			docHeader.getTanum(),
	        			docHeader.getDateCreated().toString(),
	        			docHeader.getBwlvs(),
	        			docHeader.getDateUpdated().toString(),
	        			docHeader.getDateUpdated().toString(),
	        			docHeader.getDocumentStatus().getDocumentStatusCode()};
	        	        orderHeaders.add(array);
	        }

	        csvwriter.writeAll(orderHeaders);
			csvwriter.flush();
			csvwriter.close();
			
	        return returnFileName;

	    }
}
