from __future__ import absolute_import

from celery import shared_task
from dalalbull.celery import app

from login.models import Stock_data 
import urllib2
import json
import datetime

#TODO:insert operation must be done// 52 imports??is it necessary??
#db initialisation insert the comany details initially
#urllib2 performance constraints and exception handling??
@app.task
def Update_db():
	    now = datetime.datetime.now()
	    if(now.strftime("%A")!='Sunday'):
			start_time=datetime.time(hour=10,minute=00,second=00)
			end_time=datetime.time(hour=17,minute=00,second=00)
			now = datetime.datetime.now().time()
			if(start_time<now<end_time):
				try :
					url='http://nseindia.com/live_market/dynaContent/live_watch/stock_watch/niftyStockWatch.json'
					hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
		'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
		'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
		'Accept-Encoding': 'none',
		'Accept-Language': 'en-US,en;q=0.8',
		'Connection': 'keep-alive'}
					req = urllib2.Request(url, headers=hdr) 
					response = urllib2.urlopen( req )
					json_data=json.load(response)
					company=json_data['latestData'][0]
					try :
						company=json_data['latestData'][0]
						print(company['ltp'])
						c=Stock_data.objects.get(symbol='CNX NIFTY')
						c.current_price=company['ltp'].replace(",","")
						c.high=company['high'].replace(",","")
						c.low=company['low'].replace(",","")
						c.open_price=company['open'].replace(",","")
						c.change=company['ch'].replace(",","")
						c.change_per=company['per'].replace(",","")
						c.trade_Qty=json_data['trdVolumesum'].replace(",","")
						c.trade_Value=json_data['trdValueSum'].replace(",","")
						c.save() 	
					except Stock_data.DoesNotExist :
						c=Stock_data(symbol=company['indexName'],current_price=company['ltp'].replace(",",""),high=company['high'].replace(",",""),low=company['low'].replace(",",""),open_price=company['open'].replace(",",""),change=company['ch'].replace(",",""),change_per=company['per'].replace(",",""),trade_Qty=json_data['trdVolumesum'].replace(",",""),trade_Value=json_data['trdValueSum'].replace(",",""))
						c.save()		    		
					for company in json_data['data']:
						try :						
							c=Stock_data.objects.get(symbol=company['symbol'])
							c.current_price=company['ltP'].replace(",","")
							c.high=company['high'].replace(",","")
							c.low=company['low'].replace(",","")
							c.open_price=company['open'].replace(",","")
							c.change=company['ptsC'].replace(",","")
							c.change_per=company['per'].replace(",","")
							c.trade_Qty=company['trdVol'].replace(",","")
							c.trade_Value=company['ntP'].replace(",","")
				    			c.save()
				    		except Stock_data.DoesNotExist :
							c=Stock_data(symbol=company['symbol'],current_price=company['ltP'].replace(",",""),high=company['high'].replace(",",""),low=company['low'].replace(",",""),open_price=company['open'].replace(",",""),change=company['ptsC'].replace(",",""),change_per=company['per'].replace(",",""),trade_Qty=company['trdVol'].replace(",",""),trade_Value=company['ntP'].replace(",",""))
							c.save()		    		
				except urllib2.HTTPError, e:
    						print e.fp.read()
								    	
