/**
 * 
 */
package com.ampiere.web.struts.button;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;

import org.apache.ecs.AlignType;
import org.compiere.model.MBankStatement;
import org.compiere.model.MBankStatementLine;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MPayment;
import org.compiere.util.Ctx;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;

import com.ampiere.dto.CodeValue;
import com.ampiere.search.ColBean;

/**
 * @author Shinjirito
 */
public class CreateFromStatementForm extends CreateFromBaseForm {
	private static final long serialVersionUID = -5995431459161202272L;
	protected String bankAccountLabel;
	protected String bankAccountSelected;
	protected List<CodeValue> bankAccountList;

	/**
	 *	Static Setup - set field value
	 */
	public void statInit(Ctx ctx, Timestamp ts, int maxRecNo) {
		super.statInit(ctx);
		setTitle(Msg.translate(ctx, "C_BankStatement_ID") + " .. " + Msg.translate(ctx, "CreateFrom"));
		setBankAccountLabel(Msg.translate(ctx, "C_BankAccount_ID"));

		//  load Locator
		bankAccountList = new ArrayList<CodeValue>();
		bankAccountList.add(new CodeValue("0", ""));
		int AD_Column_ID = 4917;        //  C_BankStatement.C_BankAccount_ID
//		MLookup lookup = MLookupFactory.get (ctx, getWindowNo(), 0, AD_Column_ID, DisplayType.TableDir);
		MLookup lookup = MLookupFactory.get (ctx, getWindowNo(), AD_Column_ID, DisplayType.TableDir);
		List lst = lookup.getData(true, false, false, false);
		for (int i = 0; i < lst.size(); i++) {
			KeyNamePair knp = (KeyNamePair)lst.get(i);
			if (knp != null) {
				String key = Integer.toString(knp.getKey());
				String name = knp.getName();
				bankAccountList.add(new CodeValue(key, name));
			}
		}

		//  Set Default
//		bankAccountSelected = Env.getContext(ctx, getWindowNo(), "C_BankAccount_ID");
		bankAccountSelected = "0";

//
//		//  initial Loading
//		loadBankAccount(Integer.parseInt(bankAccountSelected), ctx, ts, maxRecNo);
	}

	/**
	 *  Init Details (never called)
	 *  @param C_BPartner_ID BPartner
	 */
	protected void initBPDetails(int C_BPartner_ID)
	{
	}   //  initDetails

	/**
	 *  Load Data - Bank Account
	 *  @param C_BankAccount_ID Bank Account
	 */
	public List loadBankAccount (int C_BankAccount_ID, Ctx ctx, Timestamp ts, int maxRecNo)
	{
		log.config ("C_BankAccount_ID=" + C_BankAccount_ID);
		/**
		 *  Selected        - 0
		 *  Date            - 1
		 *  C_Payment_ID    - 2
		 *  C_Currenncy     - 3
		 *  Amt             - 4
		 */
		String sql = "SELECT p.DateTrx,p.C_Payment_ID,p.DocumentNo, p.C_Currency_ID,c.ISO_Code, p.PayAmt,"
			+ "currencyConvert(p.PayAmt,p.C_Currency_ID,ba.C_Currency_ID,?,null,p.AD_Client_ID,p.AD_Org_ID),"   //  #1
			+ " bp.Name "
			+ "FROM C_BankAccount ba"
			+ " INNER JOIN C_Payment_v p ON (p.C_BankAccount_ID=ba.C_BankAccount_ID)"
			+ " INNER JOIN C_Currency c ON (p.C_Currency_ID=c.C_Currency_ID)"
			+ " INNER JOIN C_BPartner bp ON (p.C_BPartner_ID=bp.C_BPartner_ID) "
			+ "WHERE p.Processed='Y' AND p.IsReconciled='N'"
			+ " AND p.DocStatus IN ('CO','CL','RE') AND p.PayAmt<>0"
			+ " AND p.C_BankAccount_ID=?"                              	//  #2
			+ " AND NOT EXISTS (SELECT * FROM C_BankStatementLine l " 
			//	Voided Bank Statements have 0 StmtAmt
				+ "WHERE p.C_Payment_ID=l.C_Payment_ID AND l.StmtAmt <> 0)";

		//  Get StatementDate
//		Timestamp ts = (Timestamp)p_mTab.getValue("StatementDate");
		if (ts == null) {
			ts = new Timestamp(System.currentTimeMillis());
		}

		ArrayList<ColBean> resultList = new ArrayList<ColBean>();
		try
		{
			PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
			pstmt.setTimestamp(1, ts);
			pstmt.setInt(2, C_BankAccount_ID);
			ResultSet rs = pstmt.executeQuery();
			int lineCount = 0;
			while (rs.next())
			{
				ColBean colBean = new ColBean();
				colBean.setColId(Integer.toString(lineCount));
				int beanOffset = 0;

				if (++lineCount > maxRecNo) {
					break;
				}

				//  0-Selection
				colBean.setColData(beanOffset, "false");
				colBean.setColTitle(beanOffset, Msg.translate(ctx, "Select"));
				colBean.setStyle(beanOffset, "text-align: " + AlignType.CENTER + ";");
				beanOffset++;

				//  1-DateTrx
				colBean.setColData(beanOffset, rs.getTimestamp(1));
				colBean.setColTitle(beanOffset, Msg.translate(ctx, "Date"));
				colBean.setStyle(beanOffset, "text-align: " + AlignType.LEFT + ";");
				beanOffset++;

				//  2-C_Payment_ID
				KeyNamePair pp = new KeyNamePair(rs.getInt(2), rs.getString(3));
				colBean.setColData(beanOffset, pp);
				colBean.setColTitle(beanOffset, Msg.translate(ctx, "C_Payment_ID"));
				colBean.setStyle(beanOffset, "text-align: " + AlignType.LEFT + ";");
				beanOffset++;

				//  3-Currency
				pp = new KeyNamePair(rs.getInt(4), rs.getString(5));
				colBean.setColData(beanOffset, pp);
				colBean.setColTitle(beanOffset, Msg.translate(ctx, "C_Currency_ID"));
				colBean.setStyle(beanOffset, "text-align: " + AlignType.LEFT + ";");
				beanOffset++;

				//  4-PayAmt
				colBean.setColData(beanOffset, rs.getBigDecimal(6));
				colBean.setColTitle(beanOffset, Msg.translate(ctx, "Amount"));
				colBean.setStyle(beanOffset, "text-align: " + AlignType.RIGHT + ";");
				beanOffset++;

				//  5-Conv Amt
				colBean.setColData(beanOffset, rs.getBigDecimal(7));
				colBean.setColTitle(beanOffset, Msg.translate(ctx, "ConvertedAmount"));
				colBean.setStyle(beanOffset, "text-align: " + AlignType.RIGHT + ";");
				beanOffset++;

				//  6-BParner
				colBean.setColData(beanOffset, rs.getBigDecimal(8));
				colBean.setColTitle(beanOffset, Msg.translate(ctx, "C_BPartner_ID"));
				colBean.setStyle(beanOffset, "text-align: " + AlignType.LEFT + ";");
				beanOffset++;

				resultList.add(colBean);
			}
			rs.close();
			pstmt.close();
		}
		catch (SQLException e)
		{
			log.log(Level.SEVERE, sql, e);
		}
		return resultList;
	}   //  loadBankAccount

	/**
	 *  Save Statement - Insert Data
	 *  @return true if saved
	 */
	protected boolean save(Ctx ctx, int C_BankStatement_ID, List resultList)
	{
		log.config("");

		//  fixed values
//		int C_BankStatement_ID = ((Integer)p_mTab.getValue("C_BankStatement_ID")).intValue();
		MBankStatement bs = new MBankStatement (ctx, C_BankStatement_ID, null);
		log.config(bs.toString());

		if (selectedIndex == null || selectedIndex.length() <= 0) {
			return false;
		}
		String ppp[] = selectedIndex.split("\\,");
		if (ppp == null || ppp.length <= 0) {
			return false;
		}

		//  Lines
		for (int i = 0; i < ppp.length; i++)
		{
			int idx = Integer.parseInt(ppp[i]);
			ColBean colBean = (ColBean)resultList.get(idx);
			if (colBean != null)
			{
				Timestamp trxDate = (Timestamp)colBean.getColData(1);  //  1-DateTrx
				KeyNamePair pp = (KeyNamePair)colBean.getColData(2);   //  2-C_Payment_ID
				int C_Payment_ID = pp.getKey();
				pp = (KeyNamePair)colBean.getColData(3);               //  3-Currency
				int C_Currency_ID = pp.getKey();
				BigDecimal TrxAmt = (BigDecimal)colBean.getColData(4); //  4-PayAmt
//				BigDecimal StmtAmt = (BigDecimal)colBean.getColData(5);//  5-Conv Amt
				//
				log.fine("Line Date=" + trxDate
					+ ", Payment=" + C_Payment_ID + ", Currency=" + C_Currency_ID + ", Amt=" + TrxAmt);
				//	
				MBankStatementLine bsl = new MBankStatementLine (bs);
				bsl.setStatementLineDate(trxDate);
				bsl.setPayment(new MPayment(ctx, C_Payment_ID, null));
				if (!bsl.save())
					log.log(Level.SEVERE, "Line not created #" + i);
			}   //   if selected
		}   //  for all rows
		return true;
	}   //  save

	public String getBankAccountLabel() {
		return bankAccountLabel;
	}

	public void setBankAccountLabel(String bankAccountLabel) {
		this.bankAccountLabel = bankAccountLabel;
	}

	public List<CodeValue> getBankAccountList() {
		return bankAccountList;
	}

	public void setBankAccountList(List<CodeValue> bankAccountList) {
		this.bankAccountList = bankAccountList;
	}

	public String getBankAccountSelected() {
		return bankAccountSelected;
	}

	public void setBankAccountSelected(String bankAccountSelected) {
		this.bankAccountSelected = bankAccountSelected;
	}
}
