# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt

from __future__ import unicode_literals
import webnotes
import webnotes.defaults

from webnotes.utils import cint
from webnotes import msgprint, _
from webnotes.model.doc import make_autoname


from utilities.transaction_base import TransactionBase

class DocType(TransactionBase):
	def __init__(self, doc, doclist=[]):
		self.doc = doc
		self.doclist = doclist

	def autoname(self):
		supp_master_name = webnotes.defaults.get_global_default('supp_master_name')
		
		if supp_master_name == 'Supplier Name':
			if webnotes.conn.exists("Customer", self.doc.supplier_name):
				webnotes.msgprint(_("A Customer exists with same name"), raise_exception=1)
			self.doc.name = self.doc.supplier_name
		else:
			self.doc.name = make_autoname(self.doc.naming_series + '.#####')

	def update_address(self):
		webnotes.conn.sql("""update `tabAddress` set supplier_name=%s, modified=NOW() 
			where supplier=%s""", (self.doc.supplier_name, self.doc.name))

	def update_contact(self):
		webnotes.conn.sql("""update `tabContact` set supplier_name=%s, modified=NOW() 
			where supplier=%s""", (self.doc.supplier_name, self.doc.name))

	def update_credit_days_limit(self):
		webnotes.conn.sql("""update tabAccount set credit_days = %s where name = %s""", 
			(cint(self.doc.credit_days), self.doc.name + " - " + self.get_company_abbr()))

	def on_update(self):
		if not self.doc.naming_series:
			self.doc.naming_series = ''

		self.update_address()
		self.update_contact()

		# create account head
		self.create_account_head()

		# update credit days and limit in account
		self.update_credit_days_limit()
	
	def get_payables_group(self):
		g = webnotes.conn.sql("select payables_group from tabCompany where name=%s", self.doc.company)
		g = g and g[0][0] or ''
		if not g:
			msgprint("Update Company master, assign a default group for Payables")
			raise Exception
		return g

	def add_account(self, ac, par, abbr):
		ac_bean = webnotes.bean({
			"doctype": "Account",
			'account_name':ac,
			'parent_account':par,
			'group_or_ledger':'Group',
			'company':self.doc.company,
			"freeze_account": "No",
		})
		ac_bean.ignore_permissions = True
		ac_bean.insert()
		
		msgprint(_("Created Group ") + ac)
	
	def get_company_abbr(self):
		return webnotes.conn.sql("select abbr from tabCompany where name=%s", self.doc.company)[0][0]
	
	def get_parent_account(self, abbr):
		if (not self.doc.supplier_type):
			msgprint("Supplier Type is mandatory")
			raise Exception
		
		if not webnotes.conn.sql("select name from tabAccount where name=%s and debit_or_credit = 'Credit' and ifnull(is_pl_account, 'No') = 'No'", (self.doc.supplier_type + " - " + abbr)):

			# if not group created , create it
			self.add_account(self.doc.supplier_type, self.get_payables_group(), abbr)
		
		return self.doc.supplier_type + " - " + abbr

	def validate(self):
		#validation for Naming Series mandatory field...
		if webnotes.defaults.get_global_default('supp_master_name') == 'Naming Series':
			if not self.doc.naming_series:
				msgprint("Series is Mandatory.", raise_exception=1)
	
	def create_account_head(self):
		if self.doc.company :
			abbr = self.get_company_abbr() 
			parent_account = self.get_parent_account(abbr)
						
			if not webnotes.conn.sql("select name from tabAccount where name=%s", (self.doc.name + " - " + abbr)):
				ac_bean = webnotes.bean({
					"doctype": "Account",
					'account_name': self.doc.name,
					'parent_account': parent_account,
					'group_or_ledger':'Ledger',
					'company': self.doc.company,
					'account_type': '',
					'tax_rate': '0',
					'master_type': 'Supplier',
					'master_name': self.doc.name,
					"freeze_account": "No"
				})
				ac_bean.ignore_permissions = True
				ac_bean.insert()
				
				msgprint(_("Created Account Head: ") + ac_bean.doc.name)
			else:
				self.check_parent_account(parent_account, abbr)
		else : 
			msgprint("Please select Company under which you want to create account head")
	
	def check_parent_account(self, parent_account, abbr):
		if webnotes.conn.get_value("Account", self.doc.name + " - " + abbr, 
			"parent_account") != parent_account:
			ac = webnotes.bean("Account", self.doc.name + " - " + abbr)
			ac.doc.parent_account = parent_account
			ac.save()
	
	def get_contacts(self,nm):
		if nm:
			contact_details =webnotes.conn.convert_to_lists(webnotes.conn.sql("select name, CONCAT(IFNULL(first_name,''),' ',IFNULL(last_name,'')),contact_no,email_id from `tabContact` where supplier = '%s'"%nm))
	 
			return contact_details
		else:
			return ''
			
	def delete_supplier_address(self):
		for rec in webnotes.conn.sql("select * from `tabAddress` where supplier=%s", (self.doc.name,), as_dict=1):
			webnotes.conn.sql("delete from `tabAddress` where name=%s",(rec['name']))
	
	def delete_supplier_contact(self):
		for contact in webnotes.conn.sql_list("""select name from `tabContact` 
			where supplier=%s""", self.doc.name):
				webnotes.delete_doc("Contact", contact)
	
	def delete_supplier_account(self):
		"""delete supplier's ledger if exist and check balance before deletion"""
		acc = webnotes.conn.sql("select name from `tabAccount` where master_type = 'Supplier' \
			and master_name = %s and docstatus < 2", self.doc.name)
		if acc:
			from webnotes.model import delete_doc
			delete_doc('Account', acc[0][0])
			
	def on_trash(self):
		self.delete_supplier_address()
		self.delete_supplier_contact()
		self.delete_supplier_account()
		
	def before_rename(self, olddn, newdn, merge=False):
		from accounts.utils import rename_account_for
		rename_account_for("Supplier", olddn, newdn, merge)

	def after_rename(self, olddn, newdn, merge=False):
		set_field = ''
		if webnotes.defaults.get_global_default('supp_master_name') == 'Supplier Name':
			webnotes.conn.set(self.doc, "supplier_name", newdn)
			self.update_contact()
			set_field = ", supplier_name=%(newdn)s"
		self.update_supplier_address(newdn, set_field)

	def update_supplier_address(self, newdn, set_field):
		webnotes.conn.sql("""update `tabAddress` set address_title=%(newdn)s 
			{set_field} where supplier=%(newdn)s"""\
			.format(set_field=set_field), ({"newdn": newdn}))

@webnotes.whitelist()
def get_dashboard_info(supplier):
	if not webnotes.has_permission("Supplier", "read", supplier):
		webnotes.msgprint("No Permission", raise_exception=True)
	
	out = {}
	for doctype in ["Supplier Quotation", "Purchase Order", "Purchase Receipt", "Purchase Invoice"]:
		out[doctype] = webnotes.conn.get_value(doctype, 
			{"supplier": supplier, "docstatus": ["!=", 2] }, "count(*)")
	
	billing = webnotes.conn.sql("""select sum(grand_total), sum(outstanding_amount) 
		from `tabPurchase Invoice` 
		where supplier=%s 
			and docstatus = 1
			and fiscal_year = %s""", (supplier, webnotes.conn.get_default("fiscal_year")))
	
	out["total_billing"] = billing[0][0]
	out["total_unpaid"] = billing[0][1]
	
	return out