package com.vantec.screen.service;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.vantec.screen.controller.TransactionController;
import com.vantec.screen.entity.InventoryMaster;
import com.vantec.screen.entity.InventoryStatus;
import com.vantec.screen.entity.Location;
import com.vantec.screen.entity.LocationFillingStatus;
import com.vantec.screen.entity.LocationType;
import com.vantec.screen.entity.Part;
import com.vantec.screen.entity.PickDetail;
import com.vantec.screen.entity.ReplenTask;
import com.vantec.screen.entity.Tag;
import com.vantec.screen.entity.TransactionHistory;
import com.vantec.screen.model.SaDTO;
import com.vantec.screen.repository.InventoryMasterRepository;
import com.vantec.screen.repository.InventoryStatusRepository;
import com.vantec.screen.repository.LocationFillingStatusRepository;
import com.vantec.screen.repository.LocationRepository;
import com.vantec.screen.repository.LocationTypeRepository;
import com.vantec.screen.repository.PartRepository;
import com.vantec.screen.repository.PickDetailRepository;
import com.vantec.screen.repository.ReplenTaskRepository;
import com.vantec.screen.repository.TagRepository;
import com.vantec.screen.repository.TransactionHistoryRepository;




@Service("transactionService")
public class TransactionServiceImpl implements TransactionService{
	
	private static Logger logger = LoggerFactory.getLogger(TransactionController.class);
	
	@Autowired
	private TransactionHistoryRepository transactionHistoryRepository;
	
	@Autowired
	private InventoryMasterRepository inventoryMasterRepository;
	
	@Autowired
	private PickDetailRepository pickDetailRepository;
	
	@Autowired
	private PartRepository partRepository;
	
	@Autowired
	private InventoryStatusRepository inventoryStatusRepository;
	
	@Autowired
	private TagRepository tagRepository;
	
	@Autowired
	private LocationRepository locationRepository;
	
	@Autowired
	private LocationTypeRepository locationTypeRepository;
	
	@Autowired
	private LocationFillingStatusRepository fillingStatusRepository;
	
	@Autowired
	private ReplenTaskRepository replenTaskRepository;
	

	@Transactional
	@Override
	public Boolean saOut(SaDTO saOutDTO) {

		saOutDTO.setShortCode("SA-OUT");
		
		InventoryMaster inventory = getInventory(saOutDTO.getSerialReference(), saOutDTO.getPartNumber());
		
		if(inventory != null){
			saOutDTO.setRanOrder(inventory.getRanOrOrder());
			saOutDTO.setFromLocationCode(inventory.getLocationCode());
			
			deletePickDetail(inventory);
			
			InventoryMaster updatedInventory = updateInventory(saOutDTO,inventory);
			
			Location location = null;
			if(updatedInventory.getCurrentLocation() != null){
				
				location = updatedInventory.getCurrentLocation();
				
			}else if(updatedInventory.getLocationCode() != null){
				     
				location = locationRepository.findByLocationCode(updatedInventory.getLocationCode());
			}
			
			if(location != null){
				updateLocationStatusToEmpty(location,saOutDTO);
			}
			
			recordTransaction(saOutDTO);
			return true;
		}else{
			return false;
		}
	}
	
	
	private void deletePickDetail(InventoryMaster inventory) {
		
		List<PickDetail> pickDetails = pickDetailRepository.findByInventoryMaster(inventory);
		
		for(PickDetail pickDetail:pickDetails){
				pickDetailRepository.delete(pickDetail);
		}
		
	}

	private InventoryMaster getInventory(String serialReference, String partNumber) {
		InventoryMaster inventory = inventoryMasterRepository.findBySerialReferenceAndPartNumber(serialReference, partNumber);
		return inventory;
	}

	@Transactional
	@Override
	public Boolean saIn(SaDTO saInDTO) {
		
		saInDTO.setShortCode("SA-IN");
		
		//set conversion factor
		Part part = partRepository.findByPartNumber(saInDTO.getPartNumber());
		Double txnQty = setConversionFactor(saInDTO.getQty(),part.getConversionFactor());
		saInDTO.setQty(txnQty);
		
		addInventory(saInDTO);
		
		updateLocationStatusToFilling(locationRepository.findByLocationCode(saInDTO.getToLocationCode()),saInDTO);
		
		recordTransaction(saInDTO);
		
		return true;
	}
	
    public Boolean recordTransaction(SaDTO saDTO) {
		
        TransactionHistory transactionHistory = new TransactionHistory();
        
		transactionHistory.setPartNumber(saDTO.getPartNumber());
		transactionHistory.setSerialReference(saDTO.getSerialReference());
		transactionHistory.setRanOrOrder(saDTO.getRanOrder());
		transactionHistory.setShortCode(saDTO.getShortCode());
		transactionHistory.setTransactionReferenceCode(saDTO.getShortCode());
		transactionHistory.setTxnQty(saDTO.getQty());
		transactionHistory.setReasonCode(saDTO.getReasonCode());
		transactionHistory.setDateCreated(new Date());
		transactionHistory.setCreatedBy(saDTO.getCreatedBy());
		transactionHistory.setDateUpdated(new Date());
		transactionHistory.setUpdatedBy(saDTO.getCreatedBy());
		transactionHistory.setComment(saDTO.getComment());
		
		//SA-OUT
		transactionHistory.setFromLocationCode(saDTO.getFromLocationCode());
		
		//SA-IN
		transactionHistory.setToLocationCode(saDTO.getToLocationCode());
		
		//edit Pallet
		transactionHistory.setFromPlt(saDTO.getFromPlt());
		transactionHistory.setToPlt(saDTO.getToPlt());
		
		Boolean isUpdated = transactionHistoryRepository.save(transactionHistory)!=null;
		
		return isUpdated;
		
	}
	
	
	private InventoryMaster updateInventory(SaDTO saOutDTO,InventoryMaster inventory){
		Boolean isUpdated = false;
		String locationCode = inventory.getCurrentLocation().getLocationCode();
		
		int inventoryVal = Double.compare(inventory.getInventoryQty(),saOutDTO.getQty());
		String inventoryStatus =  inventory.getInventoryStatus().getInventoryStatusCode();
		
		logger.info("status " + inventoryStatus);
		if(inventoryVal == 0 && !("MISSING").equalsIgnoreCase(inventoryStatus)){
			inventoryMasterRepository.delete(inventory);
			if(replenChecks(locationCode)){
				System.out.println("first");
				createReplen(saOutDTO,inventory);
			}
			
		}else if(inventoryVal < 0){
			logger.info("second");
			//this case is handled at U.I
		}else if(inventoryVal > 0){
			logger.info("third");
			if(inventory.getAvailableQty() == null){ inventory.setAvailableQty(inventory.getInventoryQty() - inventory.getAllocatedQty()); }
			int availableVal = Double.compare(inventory.getAvailableQty(),saOutDTO.getQty());
			
			if(availableVal == 0){
				
				inventory.setInventoryQty(inventory.getInventoryQty() - saOutDTO.getQty());
				inventory.setAvailableQty(inventory.getAvailableQty() - saOutDTO.getQty());
			}else if(availableVal < 0){
				
				inventory.setInventoryQty(inventory.getInventoryQty() - saOutDTO.getQty());
				inventory.setAvailableQty(inventory.getAvailableQty());
				inventory.setAllocatedQty(0.0);
				releaseAllocation(inventory,saOutDTO);
			}else if(availableVal > 0){
				
				inventory.setInventoryQty(inventory.getInventoryQty() - saOutDTO.getQty());
				inventory.setAvailableQty(inventory.getAvailableQty() - saOutDTO.getQty());
			}
			inventory.setDateUpdated(new Date());
			inventory.setUpdatedBy(saOutDTO.getCreatedBy());
			inventoryMasterRepository.save(inventory);
		}
		
		return inventory;
	}
	

	private Boolean createReplen(SaDTO saOutDTO, InventoryMaster inventory) {
		
		ReplenTask replenTask = new ReplenTask();
		
		
		
		Location location = inventory.getCurrentLocation();
		
		String partNumber = null;
		if(location.getPartNumber()!=null  && !("").equalsIgnoreCase(location.getPartNumber())){
			
			partNumber = location.getPartNumber();
		}else{
			
			partNumber = inventory.getPartNumber();
		}
		
		
		
		Part part = partRepository.findByPartNumber(partNumber);
		
		replenTask.setCreatedBy(saOutDTO.getCreatedBy());
		replenTask.setDateCreated(new Date());
		replenTask.setDateUpdated(new Date());
		replenTask.setUpdatedBy(saOutDTO.getCreatedBy());
		replenTask.setInUse("");
		replenTask.setPartId(part.getId());
		replenTask.setPickGroupId(inventory.getCurrentLocation().getPickGroup().getId());
		if(part.getReplenPriority()!=null && part.getReplenPriority()!=0){
			replenTask.setPriority(part.getReplenPriority());
		}else{
			replenTask.setPriority(2);
		}
		replenTask.setProcessed(false);
		replenTask.setToLocationCode(inventory.getCurrentLocation().getLocationCode());
		
		return replenTaskRepository.save(replenTask) != null;
		
	}
	
	private Boolean replenChecks(String locationCode){
		
		Location location = locationRepository.findByLocationCode(locationCode);
		if(location.getPickGroup() == null){
			return false;
		}
		InventoryStatus status = inventoryStatusRepository.findByInventoryStatusCode("OK");
		List<InventoryMaster> inventorys = inventoryMasterRepository.findByCurrentLocationAndInventoryStatus(location, status);
		Integer inventoryCaseQty = inventorys.size();
		if(location.getMaxPickFaceQty()!= null && location.getMaxPickFaceQty() > inventoryCaseQty){
			return true;
		}else{
			return false;
		}
	}


	private Boolean addInventory(SaDTO saInDTO) {
		Part part = partRepository.findByPartNumber(saInDTO.getPartNumber());
		Location location = locationRepository.findByLocationCode(saInDTO.getToLocationCode());
		InventoryStatus status = inventoryStatusRepository.findByInventoryStatusCode("OK");
		InventoryMaster inventoryMaster = inventoryMasterRepository.findBySerialReferenceAndPartNumber(saInDTO.getSerialReference(), saInDTO.getPartNumber());
		if(inventoryMaster == null){
			 inventoryMaster = new InventoryMaster();
	         inventoryMaster.setCreatedBy(saInDTO.getCreatedBy());
	         inventoryMaster.setDateCreated(new Date());
	         inventoryMaster.setAvailableQty(saInDTO.getQty());
	         inventoryMaster.setAllocatedQty(0.0);
	         inventoryMaster.setInventoryStatus(status);
	         inventoryMaster.setInventoryQty(saInDTO.getQty());
		}else{
			 inventoryMaster.setAvailableQty(inventoryMaster.getAvailableQty() + saInDTO.getQty());
	         inventoryMaster.setAllocatedQty(inventoryMaster.getAllocatedQty());
	         inventoryMaster.setInventoryQty(inventoryMaster.getInventoryQty() + saInDTO.getQty());
		}
        
		
		
        inventoryMaster.setCurrentLocation(location);
        
        inventoryMaster.setLocationCode(saInDTO.getToLocationCode());
        inventoryMaster.setPart(part);
        inventoryMaster.setPartNumber(saInDTO.getPartNumber());
        inventoryMaster.setSerialReference(saInDTO.getSerialReference());
        inventoryMaster.setRanOrOrder(saInDTO.getRanOrder());
        inventoryMaster.setUpdatedBy(saInDTO.getCreatedBy());
        inventoryMaster.setDateUpdated(new Date());
        inventoryMaster.setRecordedMissing(false);
        inventoryMaster.setVersion((long) 0);
        inventoryMaster.setConversionFactor(1000);
        if(part.getRequiresInspection()){
        	inventoryMaster.setRequiresInspection(true);
        }
        
		
		Boolean isAdded = inventoryMasterRepository.save(inventoryMaster)!=null;
		
		return isAdded;
	}
	
	private Boolean releaseAllocation(InventoryMaster inventory,SaDTO saOutDTO){
		
		Boolean isUpdated = false;
		
        List<PickDetail> pickDetails =  pickDetailRepository.findByInventoryMaster(inventory);
		
		for(PickDetail pickDetail:pickDetails){
			pickDetail.setQtyAllocated(0.0);
			pickDetail.setProcessed(true);
			pickDetail.setDateUpdated(new Date());
			pickDetail.setUpdatedBy(saOutDTO.getCreatedBy());
			isUpdated = pickDetailRepository.save(pickDetail)!=null;
		}
		return isUpdated;
		
	}

	@Override
	public String saInValidation(String partNumber, String locationCode,String serialReference) {
		
		String reseaon = "validated";
		
		
		Part part = partRepository.findByPartNumber(partNumber);
		Location location = locationRepository.findByLocationCode(locationCode);
		
		if(!location.getLocationType().getLocationArea().equalsIgnoreCase("Work")){
			
//			//Location Type Validation
//			if(!location.getLocationType().getId().equals(part.getFixedLocationType().getId())){
//				("first case");
//				reseaon = "Location Type is not valid";
//			}
//			//Zone Type Validation
//			if(!part.getFixedSubType().getId().equals(location.getLocationSubType().getId())){
//				("second case");
//				reseaon = "Location Sub Type is not valid";
//			}
			
			
			//Mixed Part Validation
			if(!location.getMultiPartLocation()){
				InventoryStatus status =  inventoryStatusRepository.findByInventoryStatusCode("PLT");
				List<InventoryMaster> inv= inventoryMasterRepository.findBylocationCodeAndInventoryStatusNotIn(locationCode, status);
				//Validate only first result as all inventory will have same part number
				if(inv.size() > 0 && !inv.get(0).getPartNumber().equalsIgnoreCase(partNumber)){
					
					reseaon = "Location not MultiPart";
				}
			}
		}
		
		if(reseaon.equalsIgnoreCase("validated")){
			InventoryMaster inventoryMaster = inventoryMasterRepository.findBySerialReferenceAndPartNumber(serialReference, partNumber);
			if(inventoryMaster != null && inventoryMaster.getInventoryStatus() != null && "PKD".equalsIgnoreCase(inventoryMaster.getInventoryStatus().getInventoryStatusCode())){
				reseaon = "Inventory Picked";
			}
		}
		
		
		inventoryMasterRepository.findByLocationCode(locationCode);
		
		return reseaon;
	}
	

	private void updateLocationStatusToEmpty(Location currentLocation,SaDTO saOutDTO) {
		List<InventoryMaster> inventorys = inventoryMasterRepository.findByLocationCode(currentLocation.getLocationCode());
		//System.out.println("invetiry size ********** " + inventorys.size());
		List<Tag> tags = tagRepository.findByCurrentLocation(currentLocation);
		
		if(tags.size() > 0){
			for(Tag tag:tags){
				tag.setCurrentLocation(null);
				tagRepository.save(tag);
			}
		}
		
		if(inventorys.size() == 0){
			Location location = locationRepository.findById(currentLocation.getId());
			LocationFillingStatus fillingStatus =  fillingStatusRepository.findByFillingCode("Empty");
			location.setLocationFillingStatus(fillingStatus);
			location.setUpdatedBy(saOutDTO.getCreatedBy());
			location.setDateUpdated(new Date());
			locationRepository.save(location);
		}
		
	}
	
	
	private void updateLocationStatusToFilling(Location currentLocation,SaDTO saInDTO) {
		
			Location location = locationRepository.findById(currentLocation.getId());
			LocationFillingStatus fillingStatus =  fillingStatusRepository.findByFillingCode("Filling");
			location.setLocationFillingStatus(fillingStatus);
			location.setUpdatedBy(saInDTO.getCreatedBy());
			location.setDateUpdated(new Date());
			locationRepository.save(location);
		
	}
	
	public Double setConversionFactor(Double qty,Integer conversionFactor) {
		return qty*conversionFactor;
	}


	@Override
	public String splitPieceValidation(String partNumber, String serialReference) {
		InventoryMaster inventory = inventoryMasterRepository.findBySerialReferenceAndPartNumber(serialReference, partNumber);
		if(inventory==null)
			return "SERIAL CANNOT BE BLANK";
		boolean isRequireInspection = inventory.getRequiresInspection();
		if(!isRequireInspection)
			return "CANNOT SPLIT A PIECE FROM A BOX THAT IS NOT WAITING INPECTION";
		Location location = inventory.getCurrentLocation();
		LocationType inventoryLocationType = location.getLocationType();
		String inventoryLocationTypeCode = inventoryLocationType.getLocationTypeCode();
		if(!("QA").equalsIgnoreCase(inventoryLocationTypeCode))
			return "CANNOT REMOVE A PIECE FROM AN INSPECT CASE OUTSIDE OF QA";
		
		return "Split Piece";
	}

}
