package com.reallinkbilling.add;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.CheckAlreadyAvailable;

public class AddNewSupplier extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 8412376686785327300L;
	
	
	private HttpSession session;
	private String supplierAddDate;
	private String supplierName;
	private String personName;
	private String mobileNumber;
	private String address;
	private String gstNumber;
	private String pinCodeNumber;
	
	private SessionMap<String,Object> sessionMap;  
	
	public String execute() throws IOException{
		 
		String result = "login";
		session=ServletActionContext.getRequest().getSession(false); 
		
	        if(session==null || session.getAttribute("login")==null){ 
	        	addActionMessage("Please Login First !!!");
	        	result = "login";
	        }  
	        else{
	        	String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    		
	        	Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;
				
				String sql = "";
				
				String db = (String) this.getSessionMap().get("db");
				
			
					try
					{
						
						connection = GetDBConnection.getDBConnection(db);
						

						sql = "SELECT "
								+ "supplier_id "
								+ "FROM "
								+ "shop_supplier_master "
								+ "WHERE "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? "
								+ "ORDER BY "
								+ "supplier_id "
								+ "DESC LIMIT 1";
						
					
					preparedStatement = connection.prepareStatement(sql);
					preparedStatement.setString(1, shopId);
					preparedStatement.setString(2, shopCode);
					
					resultSet = preparedStatement.executeQuery();
						

						int newSupplierId = 1;
						if(resultSet.next())
						{
							if(!(resultSet.getString(1) == null))
							{
								newSupplierId = resultSet.getInt(1) + 1;
								
								
							}
							else
							{
								newSupplierId = 1;
								
							}
						}
						
						
						if(resultSet != null)
						{
							resultSet.close();
							resultSet = null;
						
						}
						if(preparedStatement != null)
						{
							preparedStatement.close();
							preparedStatement = null;
						}
						
						
						sql = "INSERT INTO shop_supplier_master "
								+ "("
								+ "supplier_id,"
								+ "shop_id,"
								+ "shop_code,"
								+ "supplier_add_date,"
								+ "suplier_name,"
								+ "contact_person_name,"
								+ "contact_number,"								
								+ "supplier_address,"
								+ "gst_number,"
								+ "pin_code_number) "								
								+ "VALUES "
								+ "(?,?,?,STR_TO_DATE(?, '%d-%m-%Y'),?,?,?,?,?,?)";
						
						preparedStatement = connection.prepareStatement(sql);
						
						preparedStatement.setInt(1, newSupplierId);
						preparedStatement.setString(2, shopId);
						preparedStatement.setString(3, shopCode);
						preparedStatement.setString(4, this.getSupplierAddDate());
						preparedStatement.setString(5, this.getSupplierName().trim().toUpperCase());
						preparedStatement.setString(6, this.getPersonName().trim().toUpperCase());
						preparedStatement.setString(7, this.getMobileNumber().trim());
						preparedStatement.setString(8, this.getAddress().trim().toUpperCase());
						preparedStatement.setString(9, this.getGstNumber().trim().toUpperCase());
						preparedStatement.setString(10, this.getPinCodeNumber().trim().toUpperCase());
					
						int i = preparedStatement.executeUpdate();
						
						if(i>0)
						{
							result = "success";
							addActionMessage("Supplier details added successfully !");
						}
						else
						{
							result = "error";
							addActionError("Error ! Supplier details not added ! Please try again !");
						}
						
						
					}catch (SQLException e) {
						result = "error";
						
						addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Supplier details not added !");
					} catch (IOException e) {
						
						result = "error";						
						addActionError(e.getMessage()+" || "+e.getCause()+" || Supplier details not added !");
					}
					finally 
					{
						
						if(resultSet != null)
						{
							try {resultSet.close(); resultSet = null;} catch (SQLException e) {}
						}
						if(preparedStatement != null)
						{
							try {preparedStatement.close(); preparedStatement = null;} catch (SQLException e) {}
						}
						if(connection != null)
						{
							
							try {connection.close(); connection = null;}catch (SQLException e) {}
						}
						
					}
	        	
	        	
	        	
	        	
	        }
	        return result;
	}
	

	public void validate() {
		
		if(getSupplierName().equals("") || getPersonName().equals("") || getMobileNumber().equals("") || getAddress().equals(""))
		{
			addActionError("Please provide details for fields marked with (*) astrick!");
		}
		
		if(!hasActionErrors())
		{
			if(this.getGstNumber() == null || this.getGstNumber().equals(""))
			{
				addActionError("Please provide GST number or specify as 'NA'!");
			}
		}
		
		if(!hasActionErrors())
		{
			if(this.getPinCodeNumber() == null || this.getPinCodeNumber().equals(""))
			{
				addActionError("Please provide pincode number of specify as 'NA'!");
			}
		}

		if(!hasActionErrors())
		{
			if(!getMobileNumber().equals(""))
			{
				if(getMobileNumber().length() >10)
				{
					addActionError("Please Provide correct mobile number ! (10 digit)");
				}
			}
		}
		
		if(!hasActionErrors())
		{
			String isCustomerAdded = "false";
			
			String [] result = new String[2];
			
			result = new CheckAlreadyAvailable().checkAvaibility("shop_supplier_master", "suplier_name", "NA", this.getSupplierName().trim().toUpperCase(), this.getSessionMap());
			
			isCustomerAdded = result[0];
			
			if(isCustomerAdded.equals("true"))
			{
				addActionError("Supplier is already added with same name!");
			}				
			
		}
		
		if(!hasActionErrors())
		{
			if(!this.getMobileNumber().equals("9999999999"))
			{
				System.out.println("Hello In");
				String isCustomerAdded = "false";
				
				String [] result = new String[2];
				
				result = new CheckAlreadyAvailable().checkAvaibility("shop_supplier_master", "contact_number", "NA", this.getMobileNumber().trim().toUpperCase(), this.getSessionMap());
				
				isCustomerAdded = result[0];
				
				if(isCustomerAdded.equals("true"))
				{
					addActionError("Supplier is already added with same mobile number!");
				}			
			}
			
		}
		
		if(!hasActionErrors())
		{
			if(!this.getGstNumber().equalsIgnoreCase("NA"))
			{
				String isCustomerAdded = "false";
				
				String [] result = new String[2];
				
				String condition = "NA";
				
				result = new CheckAlreadyAvailable().checkAvaibility("shop_supplier_master", "gst_number", condition, this.getGstNumber().toUpperCase().trim(), this.getSessionMap());
				
				isCustomerAdded = result[0];
				
				if(isCustomerAdded.equals("true"))
				{
					addActionError("Supplier is already added with same GST number!");
				}				
			}
		}
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public String getSupplierAddDate() {
		return supplierAddDate;
	}

	public void setSupplierAddDate(String supplierAddDate) {
		this.supplierAddDate = supplierAddDate;
	}

	public String getSupplierName() {
		return supplierName;
	}

	public void setSupplierName(String supplierName) {
		this.supplierName = supplierName;
	}

	public String getPersonName() {
		return personName;
	}

	public void setPersonName(String personName) {
		this.personName = personName;
	}

	public String getMobileNumber() {
		return mobileNumber;
	}

	public void setMobileNumber(String mobileNumber) {
		this.mobileNumber = mobileNumber;
	}

	

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}
	
	
	
	public String getGstNumber() {
		return gstNumber;
	}


	public void setGstNumber(String gstNumber) {
		this.gstNumber = gstNumber;
	}


	public String getPinCodeNumber() {
		return pinCodeNumber;
	}


	public void setPinCodeNumber(String pinCodeNumber) {
		this.pinCodeNumber = pinCodeNumber;
	}


	public static long getSerialversionuid() {
		return serialVersionUID;
	}


	public SessionMap<String, Object> getSessionMap() {
		return sessionMap;
	}

	public void setSessionMap(SessionMap<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}
 
	public void setSession(Map<String, Object> map) {  
	    sessionMap=(SessionMap<String, Object>)map;  
	}
	
	
	

	

}
