package report_package;

import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Connection;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import main_package.DataBaseConnection;
import main_package.DataBaseMethods;
import main_package.DataBaseMethodsHemant;
import main_package.HeaderBean;
import main_package.TrialInfo;
import org.primefaces.context.RequestContext;


@ViewScoped
@ManagedBean(name="finalAccountReport")
public class FinalAccountReportBean implements Serializable
{
	
	TrialInfo selectedRow;
	ArrayList<TrialInfo> libList, assList, incList, expList, list;
	Date startDate=new Date(), endDate=new Date();
	DataBaseFinalAccountMethod dbfm=new DataBaseFinalAccountMethod();
	DecimalFormat df=new DecimalFormat("##.##");
	boolean showTB, showPL, showBS, showColumn;
	double totalDebit, totalCredit, openingDrTotal, openingCrTotal, closingDr, closingCr;
	String searchType, searchDetail, totalDebitStr, totalCreditStr, openingDrTotalStr, openingCrTotalStr, branchUserId;
	List<SelectItem> branchList = new ArrayList<SelectItem>();
	int branchId;
	DataBaseMethodsHemant dbmh = new DataBaseMethodsHemant();

	boolean disAll;
	String userType;
	
	
	public FinalAccountReportBean() 
	{
		Connection con = DataBaseConnection.JAVAConnection();
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		branchUserId = (String) ss.getAttribute("branchUserId");
		branchList = new DataBaseMethods().branchList(branchUserId,con);
		
        String cc=(String) ss.getAttribute("companyName");
        
		userType= (String) ss.getAttribute("type");
		
	    disAll= dbmh.disAllByCompanyNameUserType(userType,cc);
		try {
			con.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public void searchReport() throws ParseException
	{
		showTB=true;showPL=showBS=false;
		list=new ArrayList<>();
		Connection conn=DataBaseConnection.JAVAConnection();
		SimpleDateFormat sdfForDb=new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
		String sDate=sdfForDb.format(startDate);
		String eDate=sdfForDb.format(endDate);
		searchDetail=searchType+ " Report Between "+sdf.format(startDate)+" To "+sdf.format(endDate);
		
		if(searchType.equals("Trial Balance"))
		{
			HeaderBean hh=new HeaderBean();
			if(hh.getName().equalsIgnoreCase("UNIRAJ NIDHI LIMITED"))
			{
				showColumn=true;
			}
			else
			{
				showColumn=false;
			}
			libList=dbfm.libilityList(branchId,sDate, eDate, conn, startDate, endDate);
			assList=dbfm.tempAssetListForTB(branchId,sDate, eDate, conn, startDate, endDate);
			expList=dbfm.tempExpenseListForTB(branchId,sDate, eDate, conn);
			incList=dbfm.tempIncomeListForTB(branchId,sDate, eDate, conn, startDate, endDate);
			assList=dbfm.cashAndBankList(branchId,sDate, eDate, assList,conn, endDate);
			
			
			list.addAll(libList);
			list.addAll(expList);
			list.addAll(incList);
			list.addAll(assList);
			
			endDate.setDate(endDate.getDate()-1);
			
			totalDebit=totalCredit=openingCrTotal=openingDrTotal=closingCr=closingDr=0;
			for(int i=0;i<list.size();i++)
			{
				list.get(i).setSno(i+1);
				double diff=(list.get(i).getOpeningDr()+list.get(i).getDebit())-(list.get(i).getOpeningCr()+list.get(i).getCredit());
				diff=Double.parseDouble(df.format(diff));
				if(diff>0)
				{
					list.get(i).setClosingDr(diff);
				}
				else
				{
					list.get(i).setClosingCr(Math.abs(diff));
				}
				
				closingCr+=list.get(i).getClosingCr();
				closingDr+=list.get(i).getClosingDr();
			}
			
			closingCr=Double.parseDouble(df.format(closingCr));
			closingDr=Double.parseDouble(df.format(closingDr));
		}
		else if(searchType.equals("Profit And Loss"))
		{
			showPL=true;showTB=showBS=false;
			expList=dbfm.tempExpenseListForTB(branchId,sDate, eDate, conn);
			incList=dbfm.tempIncomeListForTB(branchId,sDate, eDate, conn, startDate, endDate);
			
			double totalExpense=0, totalIncome=0, totalPL=0;
			for(TrialInfo tt: expList)
			{
				totalExpense+=tt.getDebit();
			}
			
			for(TrialInfo tt: incList)
			{
				totalIncome+=tt.getCredit();
			}
			
			totalPL=totalIncome-totalExpense;
			
			TrialInfo tt1=new TrialInfo();
			tt1.setParticular("Net Profit");
			if(totalPL>0)
			{
				tt1.setDebit(totalPL);
			}
			expList.add(tt1);
			
			
			TrialInfo tt2=new TrialInfo();
			tt2.setParticular("Net Loss");
			if(totalPL<0)
			{
				tt2.setCredit(Math.abs(totalPL));
			}
			incList.add(tt2);
			
			list.addAll(expList);
			list.addAll(incList);
		}
		
		else
		{
			//System.out.println("bs" +searchType);
			showBS=true;showPL=showTB=false;
			HeaderBean hh=new HeaderBean();
			
//			if(!hh.getSelectedSession().equalsIgnoreCase("2018-2019"))
//			{
//				list=dbfm.createBalanceSheetList(-1,hh.getSelectedSession(), conn);
//			}
//			else
//			{
				String arr[]=hh.getSelectedSession().split("-");
				int sy=Integer.parseInt(arr[0]);
				int ey=Integer.parseInt(arr[1]);
				String fy=String.valueOf(sy-1)+"-"+String.valueOf(ey-1);
				
				//list=dbfm.createBalanceSheetList(branchId,fy, conn);
				list=new ArrayList<>();
				
				expList=dbfm.tempExpenseListForTB(branchId,sDate, eDate, conn);
				incList=dbfm.tempIncomeListForTB(branchId,sDate, eDate, conn, startDate, endDate);
				
				double totalExpense=0, totalIncome=0, totalPL=0;
				for(TrialInfo tt: expList)
				{
					totalExpense+=tt.getDebit();
				}
				
				for(TrialInfo tt: incList)
				{
					totalIncome+=tt.getCredit();
				}
				
				totalPL=totalIncome-totalExpense;
				
				TrialInfo tt=new TrialInfo();
				tt.setParticular("Net Profit/Loss");
				if(totalPL<0)
				{
					tt.setDebit(Math.abs(totalPL));
				}
				else
				{
					tt.setCredit(totalPL);
				}
				
				list.add(tt);
				
				libList=dbfm.libilityList(branchId,sDate, eDate, conn, startDate, endDate);
				assList=dbfm.tempAssetListForTB(branchId,sDate, eDate, conn, startDate, endDate);
				assList=dbfm.cashAndBankList(branchId,sDate, eDate, assList,conn, endDate);
				
				for(int i=0;i<list.size();i++)
				{
					for(int j=0;j<assList.size();j++)
					{
						
						if(list.get(i).getAssetsHead()!=null && list.get(i).getAssetsHead().equalsIgnoreCase(assList.get(j).getParticular()))
						{
							
							list.get(i).setCredit(list.get(i).getCredit()+assList.get(j).getBalance());
							break;
						}
					}
					
					for(int k=0;k<libList.size();k++)
					{
						
						if(list.get(i).getLiabilitiesHead()!=null && list.get(i).getLiabilitiesHead().equalsIgnoreCase(libList.get(k).getParticular()))
						{
							
							list.get(i).setDebit(list.get(i).getDebit()+libList.get(k).getBalance());
							break;
						}
					}
				}
				
				list.addAll(libList);
				list.addAll(assList);
			}
			
			endDate.setDate(endDate.getDate()-1);
		//}
		
		for(int i=0;i<list.size();i++)
		{
			list.get(i).setDebit(Double.parseDouble(df.format(list.get(i).getDebit())));
			list.get(i).setCredit(Double.parseDouble(df.format(list.get(i).getCredit())));
		}
		
		for(TrialInfo ff: list)
		{
			totalCredit+=ff.getCredit();
			totalDebit+=ff.getDebit();
			openingCrTotal+=ff.getOpeningCr();
			openingDrTotal+=ff.getOpeningDr();
		}
		
		totalCredit=Double.parseDouble(df.format(totalCredit));
		totalDebit=Double.parseDouble(df.format(totalDebit));
		openingCrTotal=Double.parseDouble(df.format(openingCrTotal));
		openingDrTotal=Double.parseDouble(df.format(openingDrTotal));
		
		
		totalCreditStr=BigDecimal.valueOf(totalCredit).toPlainString();
		totalDebitStr=BigDecimal.valueOf(totalDebit).toPlainString();
		openingCrTotalStr=BigDecimal.valueOf(openingCrTotal).toPlainString();
		openingDrTotalStr=BigDecimal.valueOf(openingDrTotal).toPlainString();
	}

	public void printWhole()
	{
		
		HttpSession ss=(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		ss.setAttribute("finalAccList", list);
		ss.setAttribute("searchType", searchType);
		ss.setAttribute("totalCreditStrP", totalCreditStr);
		ss.setAttribute("totalDebitStrP", totalDebitStr);
		ss.setAttribute("openingCrTotalStrP", openingCrTotalStr);
		ss.setAttribute("openingDrTotalStrP", openingDrTotalStr);
		RequestContext.getCurrentInstance().execute("window.open('printFinalAccountReport.xhtml')");
	}
	
	public void ledgerDetail()
	{
		
	}


	public Date getStartDate() {
		return startDate;
	}



	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}



	public Date getEndDate() {
		return endDate;
	}



	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}


	public ArrayList<TrialInfo> getList() {
		return list;
	}

	public void setList(ArrayList<TrialInfo> list) {
		this.list = list;
	}

	public double getTotalDebit() {
		return totalDebit;
	}

	public void setTotalDebit(double totalDebit) {
		this.totalDebit = totalDebit;
	}

	public double getTotalCredit() {
		return totalCredit;
	}

	public void setTotalCredit(double totalCredit) {
		this.totalCredit = totalCredit;
	}

	public boolean isShowTB() {
		return showTB;
	}

	public void setShowTB(boolean showTB) {
		this.showTB = showTB;
	}

	public boolean isShowPL() {
		return showPL;
	}

	public void setShowPL(boolean showPL) {
		this.showPL = showPL;
	}

	public boolean isShowBS() {
		return showBS;
	}

	public void setShowBS(boolean showBS) {
		this.showBS = showBS;
	}

	public String getSearchType() {
		return searchType;
	}

	public void setSearchType(String searchType) {
		this.searchType = searchType;
	}

	public String getSearchDetail() {
		return searchDetail;
	}

	public void setSearchDetail(String searchDetail) {
		this.searchDetail = searchDetail;
	}



	public double getOpeningDrTotal() {
		return openingDrTotal;
	}



	public void setOpeningDrTotal(double openingDrTotal) {
		this.openingDrTotal = openingDrTotal;
	}



	public double getOpeningCrTotal() {
		return openingCrTotal;
	}



	public void setOpeningCrTotal(double openingCrTotal) {
		this.openingCrTotal = openingCrTotal;
	}



	public String getTotalDebitStr() {
		return totalDebitStr;
	}



	public void setTotalDebitStr(String totalDebitStr) {
		this.totalDebitStr = totalDebitStr;
	}



	public String getTotalCreditStr() {
		return totalCreditStr;
	}



	public void setTotalCreditStr(String totalCreditStr) {
		this.totalCreditStr = totalCreditStr;
	}



	public String getOpeningDrTotalStr() {
		return openingDrTotalStr;
	}



	public void setOpeningDrTotalStr(String openingDrTotalStr) {
		this.openingDrTotalStr = openingDrTotalStr;
	}



	public String getOpeningCrTotalStr() {
		return openingCrTotalStr;
	}



	public void setOpeningCrTotalStr(String openingCrTotalStr) {
		this.openingCrTotalStr = openingCrTotalStr;
	}

	public double getClosingDr() {
		return closingDr;
	}

	public void setClosingDr(double closingDr) {
		this.closingDr = closingDr;
	}

	public double getClosingCr() {
		return closingCr;
	}

	public void setClosingCr(double closingCr) {
		this.closingCr = closingCr;
	}

	public TrialInfo getSelectedRow() {
		return selectedRow;
	}

	public void setSelectedRow(TrialInfo selectedRow) {
		this.selectedRow = selectedRow;
	}

	public boolean isShowColumn() {
		return showColumn;
	}

	public void setShowColumn(boolean showColumn) {
		this.showColumn = showColumn;
	}
	
	public String getBranchUserId() {
		return branchUserId;
	}

	public void setBranchUserId(String branchUserId) {
		this.branchUserId = branchUserId;
	}

	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 boolean isDisAll() {
		return disAll;
	}

	public void setDisAll(boolean disAll) {
		this.disAll = disAll;
	}

	public String getUserType() {
		return userType;
	}

	public void setUserType(String userType) {
		this.userType = userType;
	}

}
