package report_package;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.Writer;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import main_package.DataBaseConnection;
import main_package.DataBaseMethods;
import main_package.HeaderBean;

@ManagedBean(name="cibilReport")
@ViewScoped
public class CibilReportBean implements Serializable 
{
	ArrayList<CibilInfo> list;
	Date startDate=new Date(), searchDate=new Date();
	boolean showGroupLoan, showOtherLoan, showGuarantor, renderGuarantor, showOldCloseLoan, showFormat, showOtherLoanFormatTwo;
	String loanType,strSearchDate, payMode, currentBalanceOption, loanPaidStatus, formatType;
	List<SelectItem> branchList = new ArrayList<SelectItem>();
	int branchId, frequency;
	String branchUserId, fileName;
	String crifNo;
	String company;
	boolean txtFile=false;
	Date todayDate= new Date();
	
	// due to new format by CRIf Aug-2023
	public void checkFormatOption()
	{
		if(loanType.equalsIgnoreCase("grouploan"))
		{
			showFormat=false;
		}
		else
		{
			showFormat=true;
		}
	}
	
	public  void filetext()
	{ 
		int i=1;
		ArrayList<String> list2 = new ArrayList<>();
		list2.add("TUDF12"+getCrifNo()+"                    "+"SUNLOG"+"  "+"          "+getStrSearchDate()+"12345678                      L00000                                                ");
		for(CibilInfo cibil : list)
		{			
			
			
			String name=cibil.getFirstName();
			if(cibil.getMiddleName() != null)
			{
				name+=" "+cibil.getMiddleName();
			}
			if(cibil.getLastName() != null)
			{
			name+=" "+cibil.getLastName();
			}
			int nameLen =name.length();
			
				if(nameLen >10)
				{
				    
				}
			list2.add("PN03N0101"+nameLen+name.replaceAll("[\\r\\n]+", "").trim());
			String dob = cibil.getMemberBirthDateStr();
			int dobLen =dob.length();
			list2.add("07"+"08"+dob.replaceAll("\\s+", ""));
			list2.add("0801"+cibil.getGender().replaceAll("[\\r\\n]+", "").trim());
			
			String incomeTax = cibil.getPAN();
			int panLen =incomeTax.length();
			String voterId =cibil.getVoterId();
			int voterLen = voterId.length();
			String drivingLiec = "";
			if(cibil.getDlNo()!=null)
			{
				drivingLiec = cibil.getDlNo();
			}
			
			int drivingLen = drivingLiec.length();
			String rationCardNo="";
			if(cibil.getRationCard()!=null)
			{
				rationCardNo=cibil.getRationCard();
			}
			
			int rationLen =rationCardNo.length();
			String uid = "";
			if(cibil.getUID()!=null)
			{
				uid = cibil.getUID();
			}
			int uidNoLen= uid.length();
			String idType ="",idTypeVo ="",idTypeDr ="",idTypeRa ="",idTypeUI ="";
					
				if(panLen != 0)
				{	
					idType ="pan";
					list2.add("ID03I0101020102"+panLen+incomeTax.replaceAll("[\\r\\n]+", "").trim());
				}
				else if(voterLen != 0)
				{
					idTypeVo="voterId";
					list2.add("ID03I0101020302"+voterLen+voterId.replaceAll("[\\r\\n]+", "").trim());
				}
				else if(drivingLen != 0)
				{	
					idTypeDr ="driving";
							
					list2.add("ID03I0101020402"+drivingLen+drivingLiec.replaceAll("[\\r\\n]+", "").trim());
				}
				else if(rationLen != 0)
				{
					idTypeRa ="ration";
					list2.add("ID03I0101020502"+rationLen+rationCardNo.replaceAll("[\\r\\n]+", "").trim());
					
				}
				else if (uidNoLen != 0)
				{
					idTypeUI ="uid";
					list2.add("ID03I0101020602"+uidNoLen+uid.replaceAll("[\\r\\n]+", "").trim());
				}
				
				
				 if(voterLen != 0 && !idTypeVo.equalsIgnoreCase("voterId"))
				{
					 idTypeVo ="voterId";
					list2.add("ID03I0201020302"+voterLen+voterId.replaceAll("[\\r\\n]+", "").trim());
				}
				else if(drivingLen != 0 && !idTypeDr.equalsIgnoreCase("driving"))
				{
					idTypeDr ="driving";
					list2.add("ID03I0201020402"+drivingLen+drivingLiec.replaceAll("[\\r\\n]+", "").trim());

				}
				else if(rationLen != 0  && !idTypeRa.equalsIgnoreCase("ration"))
				{
					idTypeRa ="ration";
					list2.add("ID03I0201020502"+rationLen+rationCardNo);
					
				}
				else if (uidNoLen != 0 && !idTypeUI.equalsIgnoreCase("uid"))
				{
					idTypeUI ="uid";
					list2.add("ID03I0201020602"+uidNoLen+uid);
				}
				 
				 
				 
				 if(drivingLen != 0 && !idTypeDr.equalsIgnoreCase("driving"))
				{
					 idTypeDr ="driving";
					list2.add("ID03I0301020402"+drivingLen+drivingLiec);
				}
				 
				else if(rationLen != 0 && !idTypeRa.equalsIgnoreCase("ration"))
				{
					idTypeRa ="ration";
					list2.add("ID03I0301020502"+rationLen+rationCardNo);
					
				}
				
				else if (uidNoLen != 0 && !idTypeUI.equalsIgnoreCase("uid"))
				{
					idTypeUI ="uid";
					list2.add("ID03I0301020602"+uidNoLen+uid);
				}
								 
				 if(rationLen != 0 && !idTypeRa.equalsIgnoreCase("ration"))
				{
					 idTypeRa ="ration";
					list2.add("ID03I0401020502"+rationLen+rationCardNo);
					
				}
				 
				else if (uidNoLen != 0 && !idTypeUI.equalsIgnoreCase("uid"))
				{
					idTypeUI ="uid";
					list2.add("ID03I0401020602"+uidNoLen+uid);
				}
				
				 
				 if (uidNoLen != 0 && !idTypeUI.equalsIgnoreCase("uid"))
					{
						list2.add("ID03I0501020602"+uidNoLen+uid);
					}
				
				 
				 String telephoneNo = cibil.getMobileNo();
				 int mobileNoLen= telephoneNo.length();
				 list2.add("PT03T0101"+mobileNoLen+telephoneNo+"030200");
				 
				 String consumerAddress= cibil.getPermanentAddress()+" ";
				 
				 
				 int firstComma = consumerAddress.indexOf(' ');
			        int secondComma = consumerAddress.indexOf(' ', firstComma + 1);
			        int thirdComma = consumerAddress.indexOf(' ', secondComma + 1);
			        int len1=1; 
			        
			        
			        double ld=Math.round(consumerAddress.length()/3);
			        System.out.println(ld+"ff");
			        len1= (int) ld;

			         {
			            String part1 = consumerAddress.substring(0,len1);
			            String part2 = consumerAddress.substring(len1,len1+len1);
			            String part3 =consumerAddress.substring(len1+len1,len1+len1+len1);
			            int addressLen = part1.length();
						 String addSize="";
						 if(addressLen < 10)
						 {
							 addSize="0";
						 }
						 
						 int addressLen2 = part2.length();
						 String addSize2="";
						 if(addressLen2 < 10)
						 {
							 addSize2="0";
						 }
						 int addresssLen3 =part3.length();
						 String addSize3="";
						 if(addresssLen3 < 10)
						 {
							 addSize3="0";
						 }
						 list2.add("PA03A0101"+addSize+addressLen+part1);
						 list2.add("02"+addSize2+addressLen2+part2);
						 list2.add("03"+addSize3+addresssLen3+part3);

			            
			        } 
					 
				 list2.add("060208");
				 
				  {
					 
				 String pinCode =cibil.getPinCode();
				 int pinLen = pinCode.length();
				 System.out.println("edf"+pinCode);
				 String pinSize="";
				 if(pinLen < 10)
				 {
					 pinSize="0";
				 }
				 if(i != 1) {
				 list2.add("07"+"06"+cibil.getPinCode());
				 }
				 i++;
				 }
				 list2.add("080201");
				 String customerReportingCode= cibil.getCrifMembershipNo();
				 int CusRepCode= customerReportingCode.length();
				 String repSize="";
				 if(CusRepCode < 10)
				 {
					 repSize="0";
				 }
				 list2.add("TL04T00101"+"10"+getCrifNo());
				 
				 
					list2.add("02"+"06"+"SUNLOG");
				
				 String currentNewAccountNo =cibil.getLoanNo();
				 int accountNoLen =currentNewAccountNo.length();
				 String accSize="";
				 if(accountNoLen < 10)
				 {
					 accSize="0";
				 }
				 
				 list2.add("03"+accSize+accountNoLen+currentNewAccountNo);
				 
					 list2.add("04"+"0205");
				 
				 
				 
				list2.add("05011");
				list2.add("0808"+cibil.getLoanSanctionDateStr());
				
				if( cibil.getStrLastPayDate()!=null)
				{
				list2.add("0908"+cibil.getStrLastPayDate());
				}
				
				if( !cibil.getStrLoanCloseDate().equalsIgnoreCase("")) 
				{
					list2.add("1008"+cibil.getStrLoanCloseDate());
				}
				
				list2.add("1108"+getStrSearchDate());
				int highCreditAmount =(int) cibil.getLoanDisburseAmount();
				
				String len=String.valueOf(highCreditAmount);
				int highCreditAmountLen=len.length();
				 String creSize="";
				 if(highCreditAmountLen < 10)
				 {
					 creSize="0";
				 }
				list2.add("12"+creSize+highCreditAmountLen+highCreditAmount);
				
				int currentBalance= (int) cibil.getCurrentBalance();
				String currlen=String.valueOf(currentBalance);
				int currentBalanceLen=currlen.length();
				 String curSize="";
				 if(currentBalanceLen < 10)
				 {
					 curSize="0";
				 }
				list2.add("13"+curSize+currentBalanceLen+currentBalance);
				
				int amountOverdue = (int) cibil.getAmountOverDue();
				String aOlen =String.valueOf(amountOverdue);
				int amountOverdueLen =aOlen.length();
				 String overSize="";
				 
				 if(amountOverdueLen < 10)
				 {
					 overSize="0";
				 }
				list2.add("14"+overSize+amountOverdueLen+amountOverdue);
				
				int numberofDayPastDue=cibil.getDaysPastDue();
				String dayLen =String.valueOf(numberofDayPastDue);
				int dayPastDueLen= dayLen.length();
				 String pstSize="";
				 if(dayPastDueLen < 10)
				 {
					 pstSize="0";
				 }
				list2.add("15"+pstSize+dayPastDueLen+dayLen);
				list2.add("20011");
				
				if(cibil.getAssetsClassification() != null)
				{
					list2.add("2602"+cibil.getAssetsClassification());
				}
				
				int creditLimit =(int) cibil.getLoanDisburseAmount();
				String forlen =String.valueOf(creditLimit);
				int creditLimitLen = forlen.length();
				 String creASize="";
				 if(creditLimitLen < 10)
				 {
					 creASize="0";
				 }
				list2.add("36"+creASize+creditLimitLen+creditLimit);
				list2.add("37"+creASize+creditLimitLen+creditLimit);
				
				double rateOfIntrest = cibil.getRateOfInterest();
				String forintrestLen = String.valueOf(rateOfIntrest);
				int rateOfIntrestLen =forintrestLen.length();
				 String rateISize="";
				 if(rateOfIntrestLen < 10)
				 {
					 rateISize="0";
				 }
				
				list2.add("38"+rateISize+rateOfIntrestLen+rateOfIntrest);
				int emiAmount = (int) cibil.getInstallmentAmount();
				String foremiLen =String.valueOf(emiAmount);
				int emiAmountLen = foremiLen.length();
				 String emiSize="";
				 if(emiAmountLen < 10)
				 {
					 emiSize="0";
				 }
				list2.add("40"+emiSize+emiAmountLen+emiAmount);
				
				
				if(cibil.getWriteOffAmount() !=0.0) {
					
				int wrritenAmount = (int) cibil.getWriteOffAmount();
				String forwrritenLen =String.valueOf(wrritenAmount);
				int writtenAmountLen = forwrritenLen.length();
				 String wriSize="";
				 if(writtenAmountLen < 10)
				 {
					 wriSize="0";
				 }
				list2.add("41"+wriSize+writtenAmountLen+wrritenAmount);
				list2.add("42"+wriSize+writtenAmountLen+wrritenAmount);
				list2.add("43"+wriSize+writtenAmountLen+wrritenAmount);
				
				}
				if(cibil.getFrequencyLabel() !="")
				{
					String frequencyLabel =cibil.getFrequencyLabel();
					int frequencyLen =frequencyLabel.length();
					list2.add("4402"+frequencyLabel);
				}
				
				
				list2.add("ES02**");
				
			
	
	
			}
		list2.add("TRLR");

		
        
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();

        try {
            String fileName = "Consumer UCRF("+company+"-"+getStrSearchDate()+").txt";

            // Prepare content
            String fileContent = String.join("", list2);  // Your ArrayList<String> content here

            // Set response headers
            response.reset();
            response.setContentType("text/plain");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setCharacterEncoding("UTF-8");

            // Write content to output stream
            try (OutputStream out = response.getOutputStream();
                    Writer writer = new OutputStreamWriter(out, "UTF-8")) {

                   // Write the content as a single line
                   writer.write(fileContent);  // or writer.write(singleLine);

                   writer.flush();
               }

            // Signal JSF that response is completed
            facesContext.responseComplete();

        } catch (IOException e) {
            e.printStackTrace();
        }
		

	}
	
	public static void writeListToFile(ArrayList<String> list, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (String line : list) {
                writer.write(line);
                writer.newLine();  // write each element on a new line
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	
	public void searchReport() 
	{	
		//this boolean value for txt file
		txtFile=true;
		
		Connection conn=DataBaseConnection.JAVAConnection();
		
		startDate.setYear(startDate.getYear()-10);
		//System.out.println(startDate);
		
		if(company.equalsIgnoreCase("CRIF"))
		{
			crifNo=new DataBaseMethods().checkSMessageApiDetailFromTable("crif_no","", conn);
		}
		else if(company.equalsIgnoreCase("EXPERIAN"))
		{
			crifNo=new DataBaseMethods().checkSMessageApiDetailFromTable("experial_no","", conn);
		}
		else if(company.equalsIgnoreCase("EQUIFAX"))
		{
			crifNo=new DataBaseMethods().checkSMessageApiDetailFromTable("equifax_no","", conn);
		}
		 
		if(crifNo!=null && !crifNo.equalsIgnoreCase(""))
		{
			SimpleDateFormat cibilDtFormat=new SimpleDateFormat("ddMMyyyy");
			strSearchDate=cibilDtFormat.format(searchDate);
			if(loanType.equalsIgnoreCase("grouploan"))
			{
				list=new DataBaseReportMethods().cibilDataForGroupLoan(branchId,searchDate, payMode, currentBalanceOption, startDate, loanPaidStatus, frequency,showOldCloseLoan,company);
				showGroupLoan=true;
				showOtherLoan=false;
				showOtherLoanFormatTwo=false;
			}
			else
			{
				if(formatType.equalsIgnoreCase("1"))
				{
					list=new DataBaseReportMethods().cibilDataForOtherLoan(branchId,searchDate, loanType, payMode, currentBalanceOption, startDate, loanPaidStatus, 
							showGuarantor,frequency,showOldCloseLoan,company);
					showGroupLoan=false;
					showOtherLoan=true;
					showOtherLoanFormatTwo=false;
				}
				else
				{
					showGroupLoan=false;
					showOtherLoan=false;
					showOtherLoanFormatTwo=true;
					list=new DataBaseReportMethods().cibilDataForOtherLoanFormatTwo(searchDate, loanType, payMode, currentBalanceOption, startDate, loanPaidStatus, 
							showGuarantor,frequency,showOldCloseLoan,company,branchId);
				}
			}
		}
		else
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please Contact to Administrator for update CRIF High Mark Membership No in this Software. !!!"));
		}
		fileName=new SimpleDateFormat("dd-MM-yyyy").format(searchDate)+"_"+loanType;
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public ArrayList<CibilInfo> getList() {
		return list;
	}

	public void setList(ArrayList<CibilInfo> list) {
		this.list = list;
	}

	public Date getSearchDate() {
		return searchDate;
	}

	public void setSearchDate(Date searchDate) {
		this.searchDate = searchDate;
	}

	

	public String getLoanType() {
		return loanType;
	}

	public void setLoanType(String loanType) {
		this.loanType = loanType;
	}

	public boolean isShowGroupLoan() {
		return showGroupLoan;
	}

	public void setShowGroupLoan(boolean showGroupLoan) {
		this.showGroupLoan = showGroupLoan;
	}

	public boolean isShowOtherLoan() {
		return showOtherLoan;
	}

	public void setShowOtherLoan(boolean showOtherLoan) {
		this.showOtherLoan = showOtherLoan;
	}

	public String getStrSearchDate() {
		return strSearchDate;
	}

	public void setStrSearchDate(String strSearchDate) {
		this.strSearchDate = strSearchDate;
	}

	public String getPayMode() {
		return payMode;
	}

	public void setPayMode(String payMode) {
		this.payMode = payMode;
	}

	public String getCurrentBalanceOption() {
		return currentBalanceOption;
	}

	public void setCurrentBalanceOption(String currentBalanceOption) {
		this.currentBalanceOption = currentBalanceOption;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public String getLoanPaidStatus() {
		return loanPaidStatus;
	}

	public void setLoanPaidStatus(String loanPaidStatus) {
		this.loanPaidStatus = loanPaidStatus;
	}

	public boolean isShowGuarantor() {
		return showGuarantor;
	}

	public void setShowGuarantor(boolean showGuarantor) {
		this.showGuarantor = showGuarantor;
	}

	public boolean isRenderGuarantor() {
		return renderGuarantor;
	}

	public void setRenderGuarantor(boolean renderGuarantor) {
		this.renderGuarantor = renderGuarantor;
	}

	public List<SelectItem> getBranchList() {
		return branchList;
	}

	public void setBranchList(List<SelectItem> branchList) {
		this.branchList = branchList;
	}

	public int getBranchId() {
		return branchId;
	}

	public void setBranchId(int branchId) {
		this.branchId = branchId;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public boolean isShowFormat() {
		return showFormat;
	}

	public void setShowFormat(boolean showFormat) {
		this.showFormat = showFormat;
	}

	public boolean isShowOtherLoanFormatTwo() {
		return showOtherLoanFormatTwo;
	}

	public void setShowOtherLoanFormatTwo(boolean showOtherLoanFormatTwo) {
		this.showOtherLoanFormatTwo = showOtherLoanFormatTwo;
	}

	public String getFormatType() {
		return formatType;
	}

	public void setFormatType(String formatType) {
		this.formatType = formatType;
	}

	public boolean isShowOldCloseLoan() {
		return showOldCloseLoan;
	}

	public void setShowOldCloseLoan(boolean showOldCloseLoan) {
		this.showOldCloseLoan = showOldCloseLoan;
	}

	public int getFrequency() {
		return frequency;
	}

	public void setFrequency(int frequency) {
		this.frequency = frequency;
	}

	public boolean isTxtFile() {
		return txtFile;
	}

	public void setTxtFile(boolean txtFile) {
		this.txtFile = txtFile;
	}

	public String getCrifNo() {
		return crifNo;
	}

	public void setCrifNo(String crifNo) {
		this.crifNo = crifNo;
	}

	public String getCompany() {
		return company;
	}

	public void setCompany(String company) {
		this.company = company;
	}

	public Date getTodayDate() {
		return todayDate;
	}

	public void setTodayDate(Date todayDate) {
		this.todayDate = todayDate;
	}
	
	
}
