package com.vantec.screen.service;

import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityNotFoundException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.vantec.screen.controller.ScreenController;
import com.vantec.screen.entity.ChargeMaster;
import com.vantec.screen.entity.ChargeType;
import com.vantec.screen.entity.ContainerSortaion;
import com.vantec.screen.entity.DocumentBody;
import com.vantec.screen.entity.DocumentDetail;
import com.vantec.screen.entity.InventoryMaster;
import com.vantec.screen.entity.Location;
import com.vantec.screen.entity.LocationAisle;
import com.vantec.screen.entity.LocationColumn;
import com.vantec.screen.entity.LocationFillingStatus;
import com.vantec.screen.entity.LocationRack;
import com.vantec.screen.entity.LocationRow;
import com.vantec.screen.entity.LocationSubType;
import com.vantec.screen.entity.LocationType;
import com.vantec.screen.entity.Part;
import com.vantec.screen.entity.PickGroup;
import com.vantec.screen.entity.PruefcubePart;
import com.vantec.screen.entity.ReasonCode;
import com.vantec.screen.entity.ScanData;
import com.vantec.screen.entity.ShippingHeader;
import com.vantec.screen.entity.Tag;
import com.vantec.screen.entity.Vendor;
import com.vantec.screen.model.AisleDTO;
import com.vantec.screen.model.ChargeDTO;
import com.vantec.screen.model.ChargeTypeDTO;
import com.vantec.screen.model.CointanerSolutionDTO;
import com.vantec.screen.model.ColumnDTO;
import com.vantec.screen.model.DocumentDetailBlockDTO;
import com.vantec.screen.model.DocumentDetailsDTO;
import com.vantec.screen.model.InventoryDTO;
import com.vantec.screen.model.LocationCodeDTO;
import com.vantec.screen.model.LocationDTO;
import com.vantec.screen.model.LocationFillingStatusDTO;
import com.vantec.screen.model.LocationTypeDTO;
import com.vantec.screen.model.ManifestDTO;
import com.vantec.screen.model.PartDTO;
import com.vantec.screen.model.PickGroupDTO;
import com.vantec.screen.model.RackDTO;
import com.vantec.screen.model.ReasonCodeDTO;
import com.vantec.screen.model.RowDTO;
import com.vantec.screen.model.SaDTO;
import com.vantec.screen.model.VendorDTO;
import com.vantec.screen.model.ZoneTypeDTO;
import com.vantec.screen.repository.ChargeMasterRepository;
import com.vantec.screen.repository.ChargeTypeRepository;
import com.vantec.screen.repository.ContainerSortationRepository;
import com.vantec.screen.repository.DocumentBodyRepository;
import com.vantec.screen.repository.DocumentDetailRepository;
import com.vantec.screen.repository.InventoryMasterRepository;
import com.vantec.screen.repository.InventoryStatusRepository;
import com.vantec.screen.repository.LocationAisleRepository;
import com.vantec.screen.repository.LocationColumnRepository;
import com.vantec.screen.repository.LocationFillingStatusRepository;
import com.vantec.screen.repository.LocationRackRepository;
import com.vantec.screen.repository.LocationRepository;
import com.vantec.screen.repository.LocationRowRepository;
import com.vantec.screen.repository.LocationSubTypeRepository;
import com.vantec.screen.repository.LocationTypeRepository;
import com.vantec.screen.repository.PackTypeRepository;
import com.vantec.screen.repository.PartRepository;
import com.vantec.screen.repository.PickGroupRepository;
import com.vantec.screen.repository.ProductTypeRepository;
import com.vantec.screen.repository.PruefcubePartRepository;
import com.vantec.screen.repository.ReasonCodeRepository;
import com.vantec.screen.repository.ScanDataRepository;
import com.vantec.screen.repository.ShippingHeaderRepository;
import com.vantec.screen.repository.TagRepository;
import com.vantec.screen.repository.VendorRepository;
import com.vantec.screen.util.ScreenServiceHelper;



@Service("screenService")
public class ScreenServiceImpl implements ScreenService{
	
	 private static Logger logger = LoggerFactory.getLogger(ScreenServiceImpl.class);
	
	@Autowired
	private VendorRepository vendorRepository;
	
	@Autowired
	private PickGroupRepository pickGroupRepository;
	
	@Autowired
	private LocationRepository locationRepository;
	
	@Autowired
	private ChargeMasterRepository chargeRepository;
	
	@Autowired
	private LocationSubTypeRepository subTypeRepository;
	
	@Autowired
	private LocationRowRepository rowRepository;
	
	@Autowired
	private LocationAisleRepository aisleRepository;
	
	@Autowired 
	private LocationRackRepository rackRepository;
	
	@Autowired
	private LocationColumnRepository columnRepository;
	
	@Autowired
	private LocationTypeRepository locationTypeRepository;
	
	@Autowired
	private ChargeTypeRepository chargeTypeRepository;
	
	@Autowired
	private PackTypeRepository packTypeRepository;
	
	@Autowired
	private ChargeMasterRepository chargeMasterRepository;
	
	@Autowired
	private PartRepository partRepository;
	
	@Autowired
	private InventoryStatusRepository inventoryStatusRepository;
	
	@Autowired
	private LocationFillingStatusRepository fillingStatusRepository;
	
	@Autowired
	private ProductTypeRepository productTypeRepository;
	
	@Autowired
	private InventoryMasterRepository inventoryMasterRepository;
	
	@Autowired
	private ShippingHeaderRepository shippingHeaderRepository;
	
	@Autowired
	private DocumentDetailRepository docDetailRepo;
	
	@Autowired
	private DocumentBodyRepository docBodyRepo;
	
	@Autowired
	private ReasonCodeRepository reasonCodeRepository;
	
	@Autowired
	private ScanDataRepository scanDataRepository;
	
	@Autowired
	private LocationFillingStatusRepository locationFillingStatusRepository;
	
	@Autowired
	private TransactionService transactionService;
	
	@Autowired
	private TagRepository tagRepository;
	
	@Autowired
	private PruefcubePartRepository pruefcubePartRepository;
	
	@Autowired
	private ContainerSortationRepository containerSortationRepository;
	
	
	@Override
	public Boolean createVendor(VendorDTO vendorDTO) throws ParseException {
		vendorDTO.setStorageCharge(chargeRepository.findById(vendorDTO.getStorageChargeId()));
		vendorDTO.setReceiptCharge(chargeRepository.findById(vendorDTO.getReceiptChargeId()));
		vendorDTO.setDespatchCharge(chargeRepository.findById(vendorDTO.getDespatchChargeId()));
		vendorDTO.setDecantCharge(chargeRepository.findById(vendorDTO.getDecantChargeId()));
		vendorDTO.setInspectCharge(chargeRepository.findById(vendorDTO.getInspectChargeId()));
		vendorDTO.setTransportCharge(chargeRepository.findById(vendorDTO.getTransportChargeId()));
		vendorDTO.setVersion((long) -1);
		Vendor vendor = ScreenServiceHelper.convertVendorViewToEntity(vendorDTO,null);

        Boolean requestCompleted = vendorRepository.save(vendor) != null;
		return requestCompleted;
	}
	
	@Override
	public Boolean editVendor(VendorDTO vendorDTO) throws ParseException {
		vendorDTO.setStorageCharge(chargeRepository.findById(vendorDTO.getStorageChargeId()));
		vendorDTO.setReceiptCharge(chargeRepository.findById(vendorDTO.getReceiptChargeId()));
		vendorDTO.setDespatchCharge(chargeRepository.findById(vendorDTO.getDespatchChargeId()));
		vendorDTO.setDecantCharge(chargeRepository.findById(vendorDTO.getDecantChargeId()));
		vendorDTO.setInspectCharge(chargeRepository.findById(vendorDTO.getInspectChargeId()));
		vendorDTO.setTransportCharge(chargeRepository.findById(vendorDTO.getTransportChargeId()));
		Vendor vendor = vendorRepository.findByVendorReferenceCode(vendorDTO.getVendorCode());
		vendor = ScreenServiceHelper.convertVendorViewToEntity(vendorDTO,vendor);
		
		Boolean requestCompleted = vendorRepository.save(vendor) != null;
		return requestCompleted;
	}

	@Override
	public Boolean createCharge(ChargeDTO chargeDTO) {
		ChargeType chargeType = chargeTypeRepository.findById(chargeDTO.getChargeTypeId());
		chargeDTO.setChargeType(chargeType);
		ChargeMaster charge = ScreenServiceHelper.convertChargeViewToEntity(chargeDTO,null);
		
		Boolean requestCompleted = chargeRepository.save(charge) != null;
		return requestCompleted;
	}

	@Override
	public Boolean editCharge(ChargeDTO chargeDTO) {
		ChargeMaster charge = chargeRepository.findById(chargeDTO.getId());
		ChargeType chargeType = chargeTypeRepository.findById(chargeDTO.getChargeTypeId());
		chargeDTO.setChargeType(chargeType);
		charge = ScreenServiceHelper.convertChargeViewToEntity(chargeDTO,charge);
		
		Boolean requestCompleted = chargeRepository.save(charge) != null;
		return requestCompleted;
	}

	@Override
	public Boolean createZoneType(ZoneTypeDTO zoneTypeDTO) {
		LocationSubType zoneType = ScreenServiceHelper.convertZoneViewToEntity(zoneTypeDTO,null);
		
		Boolean requestCompleted = subTypeRepository.save(zoneType) != null;
		
		return requestCompleted;
	}

	@Override
	public Boolean editZoneType(ZoneTypeDTO zoneTypeDTO) {
		LocationSubType zoneType = subTypeRepository.findById(zoneTypeDTO.getId());
		zoneType = ScreenServiceHelper.convertZoneViewToEntity(zoneTypeDTO,zoneType);
		
		Boolean requestCompleted = subTypeRepository.save(zoneType) != null;
		return requestCompleted;
	}

	@Override
	public Boolean createRow(RowDTO rowDTO) {
		LocationRow row = ScreenServiceHelper.convertRowViewToEntity(rowDTO,null);
		
		Boolean requestCompleted = rowRepository.save(row) != null;
		return requestCompleted;
	}

	@Override
	public Boolean editRow(RowDTO rowDTO) {
		LocationRow row = rowRepository.findById(rowDTO.getId());
		row = ScreenServiceHelper.convertRowViewToEntity(rowDTO,row);
		
		Boolean requestCompleted = rowRepository.save(row) != null;
		return requestCompleted;
	}

	@Override
	public Boolean createAisle(AisleDTO aisleDTO) {
		LocationAisle aisle = ScreenServiceHelper.convertAisleViewToEntity(aisleDTO,null);
		
		Boolean requestCompleted = aisleRepository.save(aisle) != null;
		return requestCompleted;
	}

	@Override
	public Boolean editAisle(AisleDTO aisleDTO) {
		LocationAisle aisle = aisleRepository.findById(aisleDTO.getId());
		aisle = ScreenServiceHelper.convertAisleViewToEntity(aisleDTO,aisle);
		
		Boolean requestCompleted = aisleRepository.save(aisle) != null;
		return requestCompleted;
	}

	@Override
	public Boolean createColumn(ColumnDTO columnDTO) {
		LocationColumn column = ScreenServiceHelper.convertColumnViewToEntity(columnDTO,null);
		
		Boolean requestCompleted = columnRepository.save(column) != null;
		return requestCompleted;
	}

	@Override
	public Boolean editColumn(ColumnDTO columnDTO) {
		LocationColumn column = columnRepository.findById(columnDTO.getId());
		column = ScreenServiceHelper.convertColumnViewToEntity(columnDTO,column);
		
		Boolean requestCompleted = columnRepository.save(column) != null;
		return requestCompleted;
	}

	@Override
	public Boolean createLocationType(LocationTypeDTO locationTypeDTO) {
		LocationType locationType = ScreenServiceHelper.convertLocationTypeViewToEntity(locationTypeDTO,null);
		
		Boolean requestCompleted = locationTypeRepository.save(locationType) != null;
		return requestCompleted;
	}

	@Override
	public Boolean editLocationType(LocationTypeDTO locationTypeDTO) {
		LocationType locationType = locationTypeRepository.findById(locationTypeDTO.getId());
		locationType = ScreenServiceHelper.convertLocationTypeViewToEntity(locationTypeDTO,locationType);
		
		Boolean requestCompleted = locationTypeRepository.save(locationType) != null;
		return requestCompleted;
	}

	@Override
	public Boolean createPart(PartDTO partDTO) throws ParseException {
		partDTO.setVendor(vendorRepository.findById(partDTO.getVendorId()));
		partDTO.setPackType(packTypeRepository.findById(partDTO.getPackTypeId()));
		partDTO.setDecantCharge(chargeMasterRepository.findById(partDTO.getDecantChargeId()));
		partDTO.setDespatchCharge(chargeMasterRepository.findById(partDTO.getDespatchChargeId()));
		partDTO.setInspectCharge(chargeMasterRepository.findById(partDTO.getInspectChargeId()));
		partDTO.setReceiptCharge(chargeMasterRepository.findById(partDTO.getReceiptChargeId()));
		partDTO.setStorageCharge(chargeMasterRepository.findById(partDTO.getStorageChargeId()));
		partDTO.setTransportCharge(chargeMasterRepository.findById(partDTO.getTransportChargeId()));
		partDTO.setLocationType(locationTypeRepository.findById(partDTO.getLocationTypeId()));
		partDTO.setLocationSubType(subTypeRepository.findById(partDTO.getZoneTypeId()));
		Part part = ScreenServiceHelper.convertPartViewToEntity(partDTO,null);
		
		Boolean requestCompleted = partRepository.save(part) != null;
		return requestCompleted;
	}

	@Override
	public Boolean editPart(PartDTO partDTO) throws ParseException {
		Part part = partRepository.findById(partDTO.getId());
		partDTO.setVendor(vendorRepository.findById(partDTO.getVendorId()));
		partDTO.setPackType(packTypeRepository.findById(partDTO.getPackTypeId()));
		partDTO.setDecantCharge(chargeMasterRepository.findById(partDTO.getDecantChargeId()));
		partDTO.setDespatchCharge(chargeMasterRepository.findById(partDTO.getDespatchChargeId()));
		partDTO.setInspectCharge(chargeMasterRepository.findById(partDTO.getInspectChargeId()));
		partDTO.setReceiptCharge(chargeMasterRepository.findById(partDTO.getReceiptChargeId()));
		partDTO.setStorageCharge(chargeMasterRepository.findById(partDTO.getStorageChargeId()));
		partDTO.setTransportCharge(chargeMasterRepository.findById(partDTO.getTransportChargeId()));
		partDTO.setLocationType(locationTypeRepository.findById(partDTO.getLocationTypeId()));
		partDTO.setLocationSubType(subTypeRepository.findById(partDTO.getZoneTypeId()));
		part = ScreenServiceHelper.convertPartViewToEntity(partDTO,part);
		
		
		if(partDTO.getIncludeInventory() == 1){
			List<InventoryMaster> inventorys = inventoryMasterRepository.findByPart(part);
			Boolean inspect = false;
			if(partDTO.getInspect() == true){
				inspect = true;
			}
			for(InventoryMaster inventory:inventorys){
				if(inventory.getInventoryStatus() != null && 
						!inventory.getInventoryStatus().getInventoryStatusCode().equalsIgnoreCase("PKD") && 
						!inventory.getInventoryStatus().getInventoryStatusCode().equalsIgnoreCase("PLT")){
					inventory.setRequiresInspection(inspect);
					inventoryMasterRepository.save(inventory);
			     }
		    }
		}
		
		Boolean requestCompleted = partRepository.save(part) != null;
		return requestCompleted;
	}

	@Override
	public Boolean createChargeType(ChargeTypeDTO chargeTypeDTO) {
		ChargeType chargeType = ScreenServiceHelper.convertChargeTypeViewToEntity(chargeTypeDTO,null);
		
		Boolean requestCompleted = chargeTypeRepository.save(chargeType) != null;
		return requestCompleted; 
	}
	
	@Override
	public Boolean editChargeType(ChargeTypeDTO chargeTypeDTO) {
		ChargeType chargeType = chargeTypeRepository.findById(chargeTypeDTO.getId());
		chargeType = ScreenServiceHelper.convertChargeTypeViewToEntity(chargeTypeDTO,chargeType);
		Boolean requestCompleted = chargeTypeRepository.save(chargeType) != null;
		return requestCompleted;
	}

	@Override
	public Boolean createRack(RackDTO rackDTO) {
		LocationAisle aisle = aisleRepository.findById(rackDTO.getAisleId());
		rackDTO.setAisle(aisle);
		LocationRack rack = ScreenServiceHelper.convertRackViewToEntity(rackDTO,null);
		Boolean requestCompleted = rackRepository.save(rack) != null;
		return requestCompleted;
	}
	
	@Override
	public Boolean editRack(RackDTO rackDTO) {
		LocationAisle aisle = aisleRepository.findById(rackDTO.getAisleId());
		rackDTO.setAisle(aisle);
		LocationRack rack = rackRepository.findById(rackDTO.getId());
		rack = ScreenServiceHelper.convertRackViewToEntity(rackDTO,rack);
		Boolean requestCompleted = rackRepository.save(rack) != null;
		return requestCompleted;
	}

	@Override
	public Boolean deleteRow(Long rowId) {
		try{
			rowRepository.delete(rowId);
			return true;
		}catch(EmptyResultDataAccessException ex){
			throw new EntityNotFoundException(ex.getMessage());
		}catch(DataIntegrityViolationException ex){
			throw new DataIntegrityViolationException(ex.getMessage());
		}
	}

	@Override
	public Boolean deleteAisle(Long aisleId) {
		try{
			aisleRepository.delete(aisleId);
			return true;
		}catch(EmptyResultDataAccessException ex){
			throw new EntityNotFoundException(ex.getMessage());
		}catch(DataIntegrityViolationException ex){
			throw new DataIntegrityViolationException(ex.getMessage());
		}
	}
	
	@Override
	public Boolean deleteRack(Long rackId) {
		try{
			rackRepository.delete(rackId);
			return true;
		}catch(EmptyResultDataAccessException ex){
			throw new EntityNotFoundException(ex.getMessage());
		}catch(DataIntegrityViolationException ex){
			throw new DataIntegrityViolationException(ex.getMessage());
		}
	}
	
	@Override
	public Boolean deleteColumn(Long columnId) {
		try{
			columnRepository.delete(columnId);
			return true;
		}catch(EmptyResultDataAccessException ex){
			throw new EntityNotFoundException(ex.getMessage());
		}catch(DataIntegrityViolationException ex){
			throw new DataIntegrityViolationException(ex.getMessage());
		}
	}
	
	@Override
	public Boolean deleteLocationType(Long locationTypeId) {
		try{
			locationTypeRepository.delete(locationTypeId);
			return true;
		}catch(EmptyResultDataAccessException ex){
			throw new EntityNotFoundException(ex.getMessage());
		}catch(DataIntegrityViolationException ex){
			throw new DataIntegrityViolationException(ex.getMessage());
		}
	}
	
	@Override
	public Boolean deleteZoneType(Long zoneTypeId) {
		try{
			subTypeRepository.delete(zoneTypeId);
			return true;
		}catch(EmptyResultDataAccessException ex){
			throw new EntityNotFoundException(ex.getMessage());
		}catch(DataIntegrityViolationException ex){
			throw new DataIntegrityViolationException(ex.getMessage());
		}
	}

	
	private String createHashCode() {
		
		String source = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
		SecureRandom secureRandom = new SecureRandom(); 
		
		int length = 5;
		StringBuilder hashCode = new StringBuilder(length); 
		
		for (int i = 0; i < length; i++) {
			hashCode.append(source.charAt(secureRandom.nextInt(source.length())));
		}
		
		return hashCode.toString();
	}


	@Override
	public List<String> createLocation(LocationDTO locationDTO) {
		
	   List<String> locations = new ArrayList<String>(); 	
	   for(char aisleRange = locationDTO.getStartAisle(); aisleRange <= locationDTO.getEndAisle(); ++aisleRange) {
		   for(char rackRange = locationDTO.getStartRack(); rackRange <= locationDTO.getEndRack(); ++rackRange) {
			   for(Integer columnRange = locationDTO.getStartColumn(); columnRange <= locationDTO.getEndColumn(); ++columnRange){
				   for(char rowRange = locationDTO.getStartRow(); rowRange <= locationDTO.getEndRow(); ++rowRange) {
					   
					   String columnRangeStr = Integer.toString(columnRange);
					   for(int i=columnRangeStr.length();i<3;i++){
						   columnRangeStr = "0" + columnRangeStr;
					   }
					   String locationCode = Character.toString(aisleRange) + Character.toString(rackRange) + columnRangeStr + Character.toString(rowRange);
					   locations.add(locationCode);
					   String hashCode = createHashCode();
					   LocationAisle aisle = aisleRepository.findByAisleCode(Character.toString(aisleRange));
					   LocationRack rack = rackRepository.findByRackCode(Character.toString(rackRange));
					   LocationRow row = rowRepository.findByRowCode(Character.toString(rowRange));
					   LocationColumn column = columnRepository.findByColumnCode(columnRangeStr);
					   if(aisle!=null && rack!=null && row!=null && column!=null){
						   Location location = new Location();
						   location.setCreatedBy(locationDTO.getCreatedBy());
						   location.setDateCreated(new Date());
						   location.setDateUpdated(new Date());
						   location.setUpdatedBy(locationDTO.getCreatedBy());
						   location.setLocationHash(hashCode);
						   location.setInventoryStatus(inventoryStatusRepository.findById(locationDTO.getInventoryStatusId()));
						   location.setLocationAisleCode(aisle);
						   location.setLocationCode(locationCode);
						   location.setLocationCodeDescription(locationCode);
						   location.setLocationColumnCode(column);
						   location.setMaxWeight(locationDTO.getMaxWeight());
						   location.setLength(locationDTO.getLength());
						   location.setWidth(locationDTO.getWidth());
						   location.setHeight(locationDTO.getHeigth());
						   location.setVersion((long) 0);
						   location.setLocationClosed(false);
						   location.setMultiVendorLocation(false);
						   location.setPartNumber(locationDTO.getPartNumber());
						   location.setMaxPickFaceQty(locationDTO.getMaxQty());
						   location.setPickGroup(pickGroupRepository.findById(locationDTO.getPickGroupId()));
						   
						   
						   
						   if(locationDTO.getLocationFillingStatus()==null || locationDTO.getLocationFillingStatus() == false){
							   location.setLocationFillingStatus(fillingStatusRepository.findByFillingCode("Empty"));
						   }else{
							   location.setLocationFillingStatus(fillingStatusRepository.findByFillingCode("Closed"));
						   }
						   
						   
						   location.setLocationRackCode(rack);
						   location.setLocationRowCode(row);
						   location.setLocationType(locationTypeRepository.findById(locationDTO.getLocationTypeId()));
						   location.setLocationSubType(subTypeRepository.findById(locationDTO.getZoneTypeId()));
						   location.setMultiPartLocation(locationDTO.getMultiPart());
						   location.setProductType(productTypeRepository.findById(locationDTO.getProductTypeId()));
						   location.setReplenWhenEmpty(locationDTO.getReplenWhenEmpty());
						   try{
							   Boolean requestCompleted = locationRepository.save(location) != null;
						   }catch(Exception ex){
							   logger.error(ex.getMessage());
							   continue;
						   }
					   }
					   
					   
				   }
			   }
	       }
       }
		
	   return locations;
	}

	@Override
	public Boolean editLocation(LocationDTO locationDTO) {
		Location location = locationRepository.findById(locationDTO.getId());
		//location.setCreatedBy(locationDTO.getCreatedBy());
		   location.setUpdatedBy(locationDTO.getUpdatedBy());
		   location.setDateUpdated(new Date());
		   location.setInventoryStatus(inventoryStatusRepository.findById(locationDTO.getInventoryStatusId()));
		   
		   if(locationDTO.getLocationFillingStatusId() != null){
		       location.setLocationFillingStatus(fillingStatusRepository.findById(locationDTO.getLocationFillingStatusId())); 
		   }else{
			   List<InventoryMaster> inventorys = inventoryMasterRepository.findByLocationCode(location.getLocationCode());
			   location.setLocationFillingStatus(inventorys.size()>0?fillingStatusRepository.findByFillingCode("Filling"):fillingStatusRepository.findByFillingCode("Empty"));
		   }
		   
		   location.setLocationType(locationTypeRepository.findById(locationDTO.getLocationTypeId()));
		   location.setLocationSubType(subTypeRepository.findById(locationDTO.getZoneTypeId()));
		   location.setMultiPartLocation(locationDTO.getMultiPart());
		   location.setProductType(productTypeRepository.findById(locationDTO.getProductTypeId()));
		   location.setReplenWhenEmpty(locationDTO.getReplenWhenEmpty());
		   
		   location.setMaxWeight(locationDTO.getMaxWeight());
		   location.setPartNumber(locationDTO.getPartNumber());
		   location.setMaxPickFaceQty(locationDTO.getMaxQty());
		   location.setPickGroup(pickGroupRepository.findById(locationDTO.getPickGroupId()));
		   
		   location.setLength(locationDTO.getLength());
		   location.setWidth(locationDTO.getWidth());
		   location.setHeight(locationDTO.getHeigth());
		   Boolean requestCompleted = locationRepository.save(location) != null;
		return requestCompleted;
	}

	@Override
	public Boolean editInventory(InventoryDTO inventoryDTO) {
		
		Boolean isUpdated = false;
		InventoryMaster inventory = inventoryMasterRepository.findBySerialReferenceAndPartNumber(inventoryDTO.getSerialNumber(), inventoryDTO.getPartNumber());
		Location location = locationRepository.findByLocationCode(inventoryDTO.getLocationCode());
		
		if(inventory != null){
			
			//Record Transaction
			if(!inventory.getLocationCode().equalsIgnoreCase(inventoryDTO.getLocationCode())){
				
				SaDTO saDTO = new SaDTO();
				saDTO.setCreatedBy(inventoryDTO.getCurrentUser());
				saDTO.setFromLocationCode(inventory.getLocationCode());
				saDTO.setPartNumber(inventoryDTO.getPartNumber());
				saDTO.setQty(inventory.getInventoryQty());
				saDTO.setSerialReference(inventoryDTO.getSerialNumber());
				saDTO.setShortCode("STKMVFS");
				saDTO.setToLocationCode(inventoryDTO.getLocationCode());
				transactionService.recordTransaction(saDTO );
				
			}
			
			//If require insp true then inventaort status QA and vice versa
			if(inventoryDTO.getInspect()==true){
				inventoryDTO.setStatusCode("QA");
			}
			if(("QA").equalsIgnoreCase(inventoryDTO.getStatusCode())){
				inventoryDTO.setInspect(true);
			}
			
			
			//Update Inventory
			if(null != inventoryDTO.getStatusCode() && !("").equalsIgnoreCase(inventoryDTO.getStatusCode())){
				inventory.setInventoryStatus(inventoryStatusRepository.findByInventoryStatusCode(inventoryDTO.getStatusCode()));
			}
			inventory.setRequiresInspection(inventoryDTO.getInspect() == null ? inventory.getRequiresInspection() : inventoryDTO.getInspect());
			inventory.setRequiresDecant(inventoryDTO.getDecant() == null ? inventory.getRequiresDecant() : inventoryDTO.getDecant()) ;
			inventory.setUpdatedBy(inventoryDTO.getCurrentUser());
			inventory.setDateUpdated(new Date());
			inventory.setLocationCode(inventoryDTO.getLocationCode());
			inventory.setCurrentLocation(location);
			inventory.setLocation(location);
			isUpdated =  inventoryMasterRepository.save(inventory)!=null;
			
		}
		return isUpdated;
	}

	@Override
	public Boolean editManifest(ManifestDTO manifestDTO) throws ParseException {
		ShippingHeader ShippingHeader = shippingHeaderRepository.findByDocumentReference(manifestDTO.getDocumentReference());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date timeSlot = sdf.parse(manifestDTO.getExpectedDeliverTime());
		ShippingHeader.setTimeSlot(timeSlot);
		ShippingHeader.setDateUpdated(new Date());
		ShippingHeader.setUpdatedBy(manifestDTO.getUpdatedBy());
		return shippingHeaderRepository.save(ShippingHeader) != null;
	}
	
	@Override
	public Boolean editDocumentDetailQty(DocumentDetailsDTO pickDetailDTO) {
		
		Boolean isUpdated = false;
		DocumentDetail pickDetail = docDetailRepo.findOne(pickDetailDTO.getDocDetailId());
		
		if(pickDetail != null){
			pickDetail.setQtyTransacted((pickDetailDTO.getTransactedQty().intValue()));
			pickDetail.setUpdatedBy(pickDetailDTO.getUpdatedBy());
			pickDetail.setDateUpdated(new Date());
			 DocumentBody body = pickDetail.getDocumentBody();
			 body.setUpdatedBy(pickDetailDTO.getUpdatedBy());
			 body.setQtyTransacted(pickDetailDTO.getTransactedQty().intValue());
			 body.setDateUpdated(new Date());
			isUpdated = (docDetailRepo.save(pickDetail) != null && docBodyRepo.save(body) != null) ? true : false;
		}
		return isUpdated;
	}
	
	@Override
	public Boolean blockDocumentDetail(DocumentDetailBlockDTO documentDetailBlockDTO) {
		
		Boolean isBlocked = false;
		DocumentDetail docDetail = docDetailRepo.findOne(documentDetailBlockDTO.getDocDetailId());
		if(docDetail != null && docDetail.getQtyAllocated()==null)
		{
			docDetail.setQtyAllocated(0);
		}
		if(docDetail != null && docDetail.getQtyAllocated() >= 0 ){
			 docDetail.setUpdatedBy(documentDetailBlockDTO.getUpdatedBy());
			 docDetail.setDateUpdated(new Date());
			 docDetail.setBlocked(documentDetailBlockDTO.getIsBlock().equalsIgnoreCase("true")? true : false);
			 docDetail.setBlockedComment(documentDetailBlockDTO.getBlockedComment());
			 isBlocked = docDetailRepo.save(docDetail) != null;
		}
		return isBlocked;
	}
	
	@Override
	public Boolean unblockDocumentDetail(DocumentDetailBlockDTO documentDetailBlockDTO) {
		Boolean unBlocked = false;
		DocumentDetail docDetail = docDetailRepo.findOne(documentDetailBlockDTO.getDocDetailId());
		if(docDetail != null){
			 docDetail.setUpdatedBy(documentDetailBlockDTO.getUpdatedBy());
			 docDetail.setDateUpdated(new Date());
			 docDetail.setBlocked(documentDetailBlockDTO.getIsBlock().equalsIgnoreCase("true")? true : false);
			 docDetail.setBlockedComment("");
			 unBlocked = docDetailRepo.save(docDetail) != null;
		}
		return unBlocked;
	}

	public Boolean createReasonCode(ReasonCodeDTO reasonCodeDTO) {
		ReasonCode reasonCode = new ReasonCode();
		reasonCode.setVersion((long) 0);
		reasonCode.setReasonCode(reasonCodeDTO.getReasonCode());
		reasonCode.setReasonCodeDescription(reasonCodeDTO.getReasonDescription());
		reasonCode.setReasonCodeType(reasonCodeDTO.getReasonType());
		reasonCode.setDateCreated(new Date());
		reasonCode.setDateUpdated(new Date());
		reasonCode.setUpdatedBy(reasonCodeDTO.getUserId());
		return reasonCodeRepository.save(reasonCode) != null;
	}

	@Override
	public Boolean editReasonCode(ReasonCodeDTO reasonCodeDTO) {
		ReasonCode reasonCode = reasonCodeRepository.findById(reasonCodeDTO.getId());
		reasonCode.setReasonCode(reasonCodeDTO.getReasonCode());
		reasonCode.setReasonCodeDescription(reasonCodeDTO.getReasonDescription());
		reasonCode.setReasonCodeType(reasonCodeDTO.getReasonType());
		reasonCode.setDateUpdated(new Date());
		reasonCode.setUpdatedBy(reasonCodeDTO.getUserId());
		return reasonCodeRepository.save(reasonCode) != null;
	}
	public Boolean editLocationCode(LocationCodeDTO LocationCodeDTO){
		Location loc = locationRepository.findByLocationCode(LocationCodeDTO.getOldLocationCode());
		if (loc != null) {
			Location newLoc = locationRepository.findByLocationCode(LocationCodeDTO.getNewLocationCode());
			if(newLoc == null){
				loc.setLocationCode(LocationCodeDTO.getNewLocationCode());
				loc.setUpdatedBy(LocationCodeDTO.getUserId());
				loc.setDateUpdated(new Date());
				locationRepository.save(loc);
				
			}else{
				return false;
			}
		}
		return true;
		
	}
	public Boolean createLocationFillingStatus(LocationFillingStatusDTO locationFillingStatusDTO) {
		LocationFillingStatus locationFillingStatus = new LocationFillingStatus();
		locationFillingStatus.setFillingCode(locationFillingStatusDTO.getFillingCode());
		locationFillingStatus.setFillingDescription(locationFillingStatusDTO.getFillingDescription());
		locationFillingStatus.setPick(locationFillingStatusDTO.isPick());
		locationFillingStatus.setPutaway(locationFillingStatusDTO.isPutaway());
		locationFillingStatus.setDateCreated(new Date());
		locationFillingStatus.setDateUpdated(new Date());
		locationFillingStatus.setCreatedBy(locationFillingStatusDTO.getUserId());
		locationFillingStatus.setUpdatedBy(locationFillingStatusDTO.getUserId());
		return locationFillingStatusRepository.save(locationFillingStatus) != null;
	}

	public Boolean editLocationFillingStatus(LocationFillingStatusDTO locationFillingStatusDTO) {
		LocationFillingStatus locationFillingStatus = locationFillingStatusRepository.findById(locationFillingStatusDTO.getFillingStatusId());
		locationFillingStatus.setFillingCode(locationFillingStatusDTO.getFillingCode());
		locationFillingStatus.setFillingDescription(locationFillingStatusDTO.getFillingDescription());
		locationFillingStatus.setPick(locationFillingStatusDTO.isPick());
		locationFillingStatus.setPutaway(locationFillingStatusDTO.isPutaway());
		locationFillingStatus.setDateCreated(new Date());
		locationFillingStatus.setDateUpdated(new Date());
		locationFillingStatus.setUpdatedBy(locationFillingStatusDTO.getUserId());
		return locationFillingStatusRepository.save(locationFillingStatus) != null;
	}

	@Override
	public Boolean createPickGroup(PickGroupDTO pickGroupDTO) {
		PickGroup pickGroup = new PickGroup();
		pickGroup.setVersion((long) 0);
		pickGroup.setPickGroupCode(pickGroupDTO.getPickGroupCode());
		pickGroup.setPickGroupDescription(pickGroupDTO.getPickGroupDescription());
		pickGroup.setActive(true);
		pickGroup.setDateCreated(new Date());
		pickGroup.setLastUpdated(new Date());
		pickGroup.setUpdatedBy(pickGroupDTO.getUserId());
		pickGroup.setPallet(pickGroupDTO.getPallet());
		
//		List<InventoryMaster> inventorys = inventoryMasterRepository.findByTagReferenceLike("REP%");
//		if(inventorys == null || inventorys.size() == 0){
//			pickGroup.setPallet(pickGroupDTO.getPallet());
//		}
		if(pickGroup.getPallet()==true){
			pickGroup.setMaxCaseQty(pickGroupDTO.getMaxCaseQty());
		}else{
			pickGroup.setMaxCaseQty(1);
		}
		return pickGroupRepository.save(pickGroup)!=null;
	}

	@Override
	public Boolean editPickGroup(PickGroupDTO pickGroupDTO) {
		
		PickGroup pickGroup = pickGroupRepository.findById(pickGroupDTO.getId());
		pickGroup.setPickGroupCode(pickGroupDTO.getPickGroupCode());
		pickGroup.setAltPickGroupCode(pickGroupDTO.getAltPickGroup());
		pickGroup.setPickGroupDescription(pickGroupDTO.getPickGroupDescription());
		pickGroup.setLastUpdated(new Date());
		pickGroup.setUpdatedBy(pickGroupDTO.getUserId());
		pickGroup.setPallet(pickGroupDTO.getPallet());
		pickGroup.setSortByLocation(pickGroupDTO.getSortByLocation());
	
		if(pickGroup.getPallet()==true){
			pickGroup.setMaxCaseQty(pickGroupDTO.getMaxCaseQty());
		}else{
			pickGroup.setMaxCaseQty(1);
		}
		return pickGroupRepository.save(pickGroup)!=null;
	}

	@Override
	public Boolean deleteScanData(Long id) {
		ScanData scanData = scanDataRepository.findById(id);
		if(scanData != null){
			scanDataRepository.delete(scanData);
		}
		return true;
	}

	@Override
	public String deleteLocation(Long locationId) {
		
		
		Location location = locationRepository.findById(locationId);
		
		List<InventoryMaster> invs = inventoryMasterRepository.findByLocationCode(location.getLocationCode());
		List<InventoryMaster> inventorys = inventoryMasterRepository.findByLocation(location);
		List<InventoryMaster> inventoryMasters = inventoryMasterRepository.findByCurrentLocation(location);
		
		if(invs.size() > 0 || inventorys.size() > 0 || inventoryMasters.size() > 0){
			return "Cannot delete location with existing inventory";
		}else{;
			locationRepository.delete(location);
			return "Location Deleted";
		}
	}

	@Override
	public Boolean transferPallet(InventoryDTO inventoryDTO) {
		
		Boolean isUpdated = false;
		System.out.println("from pallet " + inventoryDTO.getFromPlt());
		List<InventoryMaster> inventorys = inventoryMasterRepository.findByTagReference(inventoryDTO.getFromPlt());
		System.out.println("size "  + inventorys.size());
		
		if(inventorys.size()>0){
			
			//Record Transaction
				SaDTO saDTO = new SaDTO();
				saDTO.setCreatedBy(inventoryDTO.getCurrentUser());
				saDTO.setShortCode("PLTMVFS");
				saDTO.setFromPlt(inventoryDTO.getFromPlt());
				saDTO.setToPlt(inventoryDTO.getFromPlt());
				saDTO.setToLocationCode(inventoryDTO.getLocationCode());
				saDTO.setFromLocationCode(inventorys.get(0).getLocationCode());
				saDTO.setQty(0.0);
				saDTO.setComment(inventoryDTO.getComment());
				transactionService.recordTransaction(saDTO);
			
			    
				Location location = locationRepository.findByLocationCode(inventoryDTO.getLocationCode());
				for(InventoryMaster inventory:inventorys){
					inventory.setLocation(location);
					inventory.setLocationCode(inventoryDTO.getLocationCode());
					inventory.setCurrentLocation(location);
					inventory.setUpdatedBy(inventoryDTO.getCurrentUser());
					inventory.setDateUpdated(new Date());
					inventoryMasterRepository.save(inventory);
					
				}
				isUpdated = true;
		}
		return isUpdated;
	}
	
	@Override
	public String updateManifestPrinterFlag(String documentReference, Boolean isPrinted, String userId) {
		
		ShippingHeader shipping = shippingHeaderRepository.findByDocumentReference(documentReference);
		System.out.println("shipping" + shipping);
		shipping.setIsPrinted(isPrinted);
		shipping.setUpdatedBy(userId);
		shipping.setDateUpdated(new Date());
		shippingHeaderRepository.save(shipping);
		return "Manifest Printer Updated";
	}

	@Override
	public String setPruefcubePartProcessed(String partNumber, String userId) {
		PruefcubePart  pruefcubePart = pruefcubePartRepository.findByPartNumber(partNumber);
		pruefcubePart.setProcessed(true);
		pruefcubePart.setLastUpdatedBy(userId);
		pruefcubePart.setLastUpdated(new Date());
		pruefcubePartRepository.save(pruefcubePart);
		return "PruefcubePart Processed";
	}

	@Override
	public String deletePruefcubePart(String partNumber) {
		PruefcubePart  pruefcubePart = pruefcubePartRepository.findByPartNumber(partNumber);
		pruefcubePartRepository.delete(pruefcubePart);
		return "pruefcobe part delete";
	}

	@Override
	public String createContainerSortation(CointanerSolutionDTO cointanerSolutionDTO) {
		
		ContainerSortaion cointainerSortation = new ContainerSortaion();
		cointainerSortation.setPackCode(cointanerSolutionDTO.getPackCode());
		cointainerSortation.setAdditionalPackaging(cointanerSolutionDTO.getAdditionalPackaging());
		cointainerSortation.setQty(cointanerSolutionDTO.getQty());
		cointainerSortation.setDestination(cointanerSolutionDTO.getDestination());
		cointainerSortation.setLocationCode(cointanerSolutionDTO.getLocationCode());
		cointainerSortation.setDateCreated(new Date());
		cointainerSortation.setCreatedBy(cointanerSolutionDTO.getUserId());
		cointainerSortation.setLastUpdatedDate(new Date());
		cointainerSortation.setLastUpdatedBy(cointanerSolutionDTO.getUserId());
		containerSortationRepository.save(cointainerSortation);
		
		return "Container Sortation Created";
	}

	@Override
	public String editContainerSortation(CointanerSolutionDTO cointanerSolutionDTO) {
		
		ContainerSortaion cointainerSortation = containerSortationRepository.findById(cointanerSolutionDTO.getId());
		
		if(cointainerSortation!=null){
			
			cointainerSortation.setPackCode(cointanerSolutionDTO.getPackCode());
			cointainerSortation.setAdditionalPackaging(cointanerSolutionDTO.getAdditionalPackaging());
			cointainerSortation.setQty(cointanerSolutionDTO.getQty());
			cointainerSortation.setDestination(cointanerSolutionDTO.getDestination());
			cointainerSortation.setLocationCode(cointanerSolutionDTO.getLocationCode());
			cointainerSortation.setLastUpdatedDate(new Date());
			cointainerSortation.setLastUpdatedBy(cointanerSolutionDTO.getUserId());
			containerSortationRepository.save(cointainerSortation);
		}
		
		return "Container Sortation Edited";
	}





}
