#!/usr/bin/env python
# vim: set fileencoding=utf-8 :

import sys, os
sys.path.insert(1, os.path.join(sys.path[0], '../..'))
sys.path.insert(1, os.path.join(sys.path[0], '../../..'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from logistics.models import Task
from logistics.models import ServiceLogisticsUparam as Contract
from datetime import datetime
from decimal import Decimal

ALLOWED_COMMANDS = (
		'assign_engineers_to_new_tasks',
		'assign_engineers_to_rejected_tasks',
		'write_off_day_payments',
		)

def show_help():
	global ALLOWED_COMMANDS
	print """Syntax of using:
dispatcher-assistant <command>

command is some of it:
	%s
""" % '\n\t'.join(ALLOWED_COMMANDS)

def get_intersection_datetime(d1, d2, d3, d4):
	if d2 < d3 or d4 < d1:
		return None
	if d1 > d3:
		i1 = d1
	else:
		i1 = d3
	if d2 > d4:
		i2 = d4
	else:
		i2 = d2
	if i2 > i1:
		return i2-i1
	else:
		return i1-i2

if len(sys.argv) != 2 or not sys.argv[1] in ALLOWED_COMMANDS:
	print "Wrong syntax"
	show_help()
	exit(1)

command = sys.argv[1]

if command == 'assign_engineers_to_new_tasks':
	Task().assign_engineers_to_new_tasks()
elif command == 'assign_engineers_to_rejected_tasks':
	Task().assign_engineers_to_rejected_tasks()
elif command == 'write_off_day_payments':
	from django.db.models import F
	for c in Contract.objects.filter(	type=1, # Only abonement
						last_write_off__lt=F('end_date_time'),
						unlimit_service=True): 
		d1 = c.start_date_time
		d2 = c.end_date_time

		d3 = c.last_write_off or d1
		d4 = datetime.now()
		i = get_intersection_datetime(d1,d2,d3,d4)
		print "i.days=%s" % i.days
		if i:
			cost = c.get_cost()
			print "cost=%s" % cost
			import calendar
			days_in_month = calendar.monthrange(c.last_write_off.year, c.last_write_off.month)[1]
			print "dim=%s" % days_in_month

			c.client.balance -= Decimal(i.days)*cost/Decimal(days_in_month)
			c.last_write_off = d4
			c.save()
			c.client.save()
