def send_notification(assigned_user_id, title, task_id):
	device_token_find = device_token.find_one({"userid": assigned_user_id})
	if device_token_find is not None:
		registration_id = device_token_find['token']
		message_title = "You just got a new task"
		message_body = title

		tasks_cursor =  task_collection.find({"id": task_id},{"_id":0,"audit_log":0, "schedule_date_operation":0})
		update_date_time = datetime.datetime.now()
		task        = {}
		if tasks_cursor.count()!=0:
			for task in tasks_cursor:
				total_comment = comment_collection.find({"task_id": task['id']}).count()
				get_last_read_datetime   = last_read_comments.find_one({"id": assigned_user_id, "task_id": task['id']})
				if get_last_read_datetime is not None:
					unread_comment = comment_collection.find({"created_at":{"$gte": get_last_read_datetime['last_read_datetetime']}}).count()
					task['unread_comment'] = unread_comment
				else:
					task['unread_comment'] = total_comment

				task['total_comments'] = total_comment
				extra_kwargs = {
					'priority': 'high'
				}

				print(task)
				result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body,data_message=task, extra_kwargs=extra_kwargs, click_action="FCM_PLUGIN_ACTIVITY")
def new_comment():
	params  	 = request.json
	

	engineer_id 	 = params['enginneer_id']

	is_active= engineer_collection.find({"id":engineer_id, "is_active":True}).count()

	if(is_active == 0):
		return jsonify({"message" : "Deactivated"}), 401

	tasks_cursor     =  task_collection.find({"assigned_user_id": engineer_id, "task_status":"assigned"},{"_id":0, "audit_log":0})
	update_date_time = datetime.datetime.now()
	tasks            = []
	if tasks_cursor.count()!=0:

		for task in tasks_cursor:
			total_comment = comment_collection.find({"task_id": task['id']}).count()
			get_last_read_datetime   = last_read_comments.find_one({"id": engineer_id, "task_id": task['id']})
			if get_last_read_datetime is not None:
				unread_comment = comment_collection.find({"created_at":{"$gte": get_last_read_datetime['last_read_datetetime']},'task_id': task['id']}).count()
				task['unread_comment'] = unread_comment

			else:
				task['unread_comment'] = total_comment

			task['total_comments'] = total_comment
			tasks.append(task)

			last_read_comments.update({"id": engineer_id, "task_id": task['id']},{"$set":{"last_read_datetetime":str(datetime.datetime.now())}})
			
		return jsonify({"message" : "tasks found", "tasks" : tasks}), 200
	else :
		notificaion_list_to_show = []
		return jsonify({"message" : "tasks found", "tasks" : tasks}), 200
def admin_new_comment():
	params  	 = request.json
	# user_id 	 = params['user_id']
	# secret_hash  = params['secret_hash']
	print("--------params-----------")
	print(params)

	engineer_id  = params.get('enginneer_id')

	update_date_time = str(datetime.datetime.now())
	get_last_read_datetime  = engineer_collection.find_one({"id": engineer_id},{'_id':0})
	print("----------------- get_last_read_datetime ------------------")
	print(get_last_read_datetime)
	
	last_read_datetime = update_date_time
	if "last_notification_datetetime" in get_last_read_datetime:

		last_read_datetime = get_last_read_datetime['last_notification_datetetime']
	
	abc = engineer_collection.update({"id": engineer_id},{"$set":{"last_notification_datetetime": update_date_time}})

	print("-------- abc admin -----------")
	print(abc)

	notificaion_list_to_show = []
	notification_to_show = notification_list.find({"time":{"$gte": last_read_datetime}},{'_id':0})
	for notificaionList in notification_to_show:
		notificaion_list_to_show.append(notificaionList)

	tasks_cursor     =  task_collection.find({"updated_at":{"$gte":last_read_datetime}},{"_id":0})
	update_date_time =  datetime.datetime.now()
	tasks            = []
	result = {}
	if tasks_cursor.count()!=0:
		for task in tasks_cursor:
			total_comment = comment_collection.find({"task_id": task['id']}).count()
			get_last_read_datetime   = last_read_comments.find_one({"id": engineer_id, "task_id": task['id']})
			if get_last_read_datetime is not None:
				unread_comment = comment_collection.find({"created_at":{"$gte": get_last_read_datetime['last_read_datetetime']},'task_id': task['id']}).count()
				task['unread_comment'] = unread_comment

			else:
				task['unread_comment'] = total_comment

			task['total_comments'] = total_comment
			tasks.append(task)

		result['tasks'] = tasks
		

		result['notification'] = notificaion_list_to_show
		return jsonify(result), 200
	else :
		return jsonify(result), 200
def query_date_wise_preset():
	params = request.json
	query_date = params.get("query_date")
	param_status = params.get("status")
	user_id    = request.cookies['user_id']
	start_date = params.get("start_date")
	end_date = params.get("end_date")
	

	query_status_a = None
	query_status = []
	
	for k,v in param_status.items():
		if v == True:
			query_status.append(k)

	if "all" in query_status:
		query_status.remove("all")

	if query_date == "custom":
		start_date_array = start_date.split("-");
		start_date       = datetime.datetime(int(start_date_array[2]),int(start_date_array[1]),int(start_date_array[0]))
		end_date_array   = end_date.split("-");
		end_date       = datetime.datetime(int(end_date_array[2]),int(end_date_array[1]),int(end_date_array[0]))
	
	

	tasks = []
	
	today_datetime = datetime.datetime.today().strftime('%d-%m-%Y')

	if query_date == "today":
		pass
		# tasks_cursor =  task_collection.find({"schedule_date":{"$eq": today_datetime},"task_status": {"$in": query_status}},{"_id":0}).skip(0).limit(100)

	elif query_date == "last_30":
		
		tasks_cursor = task_collection.find({"schedule_date_operation":{"$gt": (datetime.datetime.today() - timedelta(days=29)),"$lt": datetime.datetime.today() },"task_status": {"$in": query_status}},{"_id":0})
		
	elif query_date == "last_7":
		tasks_cursor = task_collection.find({"schedule_date_operation":{"$gt": (datetime.datetime.today() - timedelta(days=7)),"$lt":datetime.datetime.today()},"task_status": {"$in": query_status}},{"_id":0})

	elif query_date == "next_30":
		tasks_cursor = task_collection.find({"schedule_date_operation":{"$gt": datetime.datetime.today() ,"$lte":(datetime.datetime.today() + timedelta(days=29))},"task_status": {"$in": query_status}},{"_id":0})
		
	elif query_date == "next_7":
		tasks_cursor = task_collection.find({"schedule_date_operation":{"$gt": datetime.datetime.today() ,"$lte":(datetime.datetime.today() + timedelta(days=7))},"task_status": {"$in": query_status}},{"_id":0})
		
	elif query_date == "custom":
		tasks_cursor = task_collection.find({"schedule_date_operation":{"$gte": start_date ,"$lte": end_date },"task_status": {"$in": query_status}},{"_id":0})
		

	if query_date == 'today':
		tasks        = []
		# user_id         = request.cookies['user_id']
		
		# today_datetime = datetime.datetime.today().strftime('%d-%m-%Y')
		tasks_cursor =  task_collection.find({"schedule_date":{"$eq": today_datetime},"task_status": {"$in": query_status}},{"_id":0}).skip(0).limit(100)
		for task in tasks_cursor:
			total_comment = comment_collection.find({"task_id": task['id']}).count()
			task['total_comments'] = total_comment

			get_last_read_datetime   = last_read_comments.find_one({"id": user_id, "task_id": task['id']})
			print(get_last_read_datetime)
			if get_last_read_datetime is not None:
				unread_comment = comment_collection.find({"created_at":{"$gte": get_last_read_datetime['last_read_datetetime']},'task_id': task['id']}).count()
				print(unread_comment)
				task['unread_comment'] = unread_comment
			else:
				task['unread_comment'] = total_comment

			tasks.append(task)

		tasks_cursor = task_collection.find({"schedule_date_operation":{"$lt": (datetime.datetime.today())},"schedule_date":{"$ne":today_datetime},"task_status":{"$ne":STATUS[3]}},{"_id":0}).skip(0).limit(100)

		for task in tasks_cursor:
			task['total_comments'] = comment_collection.find({"task_id": task['id']}).count()
			total_comment = comment_collection.find({"task_id": task['id']}).count()
			task['total_comments'] = total_comment
			get_last_read_datetime = None
			get_last_read_datetime   = last_read_comments.find_one({"id": user_id, "task_id": task['id']})
			if get_last_read_datetime is not None:
				unread_comment = comment_collection.find({"created_at":{"$gte": get_last_read_datetime['last_read_datetetime']},'task_id': task['id']}).count()
				task['unread_comment'] = unread_comment

			else:
				task['unread_comment'] = total_comment
				
			tasks.append(task)


		return jsonify({"message" : "All task list found " , "tasks" : tasks }), 200
	else:


		for task in tasks_cursor:
			total_comment = comment_collection.find({"task_id": task['id']}).count()
			task['total_comments'] = total_comment

			get_last_read_datetime   = last_read_comments.find_one({"id": user_id, "task_id": task['id']})
			print(get_last_read_datetime)
			if get_last_read_datetime is not None:
				unread_comment = comment_collection.find({"created_at":{"$gte": get_last_read_datetime['last_read_datetetime']},'task_id': task['id']}).count()
				print(unread_comment)
				task['unread_comment'] = unread_comment
			else:
				task['unread_comment'] = total_comment

			tasks.append(task)


		for task in tasks_cursor:
			task['total_comments'] = comment_collection.find({"task_id": task['id']}).count()
			total_comment = comment_collection.find({"task_id": task['id']}).count()
			task['total_comments'] = total_comment
			get_last_read_datetime = None
			get_last_read_datetime   = last_read_comments.find_one({"id": user_id, "task_id": task['id']})
			if get_last_read_datetime is not None:
				unread_comment = comment_collection.find({"created_at":{"$gte": get_last_read_datetime['last_read_datetetime']},'task_id': task['id']}).count()
				task['unread_comment'] = unread_comment

			else:
				task['unread_comment'] = total_comment
				
			tasks.append(task)


		return jsonify({"message" : "All task list found " , "tasks" : tasks }), 200
def get():
	params       = request.json
	engineer_id  = params['engineer_id']
	# user_id 	 = params['user_id']
	# secret_hash  = params['secret_hash']
	offset 		 = params['offset']
	#validation on userid and secret hash
	if engineer_id   == 0 :
		# that means that we have to retrun all the tasks 
		tasks        = []
		user_id         = request.cookies['user_id']
		
		today_datetime = datetime.datetime.today().strftime('%d-%m-%Y')
		tasks_cursor =  task_collection.find({"schedule_date":{"$eq": today_datetime}},{"_id":0}).skip(offset).limit(100)
		for task in tasks_cursor:
			total_comment = comment_collection.find({"task_id": task['id']}).count()
			task['total_comments'] = total_comment

			get_last_read_datetime   = last_read_comments.find_one({"id": user_id, "task_id": task['id']})
			print(get_last_read_datetime)
			if get_last_read_datetime is not None:
				unread_comment = comment_collection.find({"created_at":{"$gte": get_last_read_datetime['last_read_datetetime']},'task_id': task['id']}).count()
				print(unread_comment)
				task['unread_comment'] = unread_comment
			else:
				task['unread_comment'] = total_comment

			tasks.append(task)

		tasks_cursor = task_collection.find({"schedule_date_operation":{"$lt": (datetime.datetime.today())},"schedule_date":{"$ne":today_datetime},"task_status":{"$ne":STATUS[3]}},{"_id":0}).skip(offset).limit(100)

		for task in tasks_cursor:
			task['total_comments'] = comment_collection.find({"task_id": task['id']}).count()
			total_comment = comment_collection.find({"task_id": task['id']}).count()
			task['total_comments'] = total_comment
			get_last_read_datetime = None
			get_last_read_datetime   = last_read_comments.find_one({"id": user_id, "task_id": task['id']})
			if get_last_read_datetime is not None:
				unread_comment = comment_collection.find({"created_at":{"$gte": get_last_read_datetime['last_read_datetetime']},'task_id': task['id']}).count()
				task['unread_comment'] = unread_comment

			else:
				task['unread_comment'] = total_comment
				
			tasks.append(task)


		return jsonify({"message" : "All task list found " , "tasks" : tasks }), 200

	else :
		# it means that we need to return the tasks for that specific engineer 
		tasks_cursor =  task_collection.find({"assigned_user_id": engineer_id, "task_status":"assigned"},{"_id":0}).skip(offset).limit(100)
		update_date_time = datetime.datetime.now()
		tasks        = []
		if tasks_cursor.count()!=0:
			for task in tasks_cursor:
				total_comment = comment_collection.find({"task_id": task['id']}).count()
				get_last_read_datetime   = last_read_comments.find_one({"id": engineer_id, "task_id": task['id']})
				if get_last_read_datetime is not None:
					unread_comment = comment_collection.find({"created_at":{"$gte": get_last_read_datetime['last_read_datetetime']},'task_id': task['id']}).count()
					task['unread_comment'] = unread_comment

				else:
					task['unread_comment'] = total_comment
				task['total_comments'] = total_comment
				tasks.append(task)

			return jsonify({"message" : "tasks found", "tasks" : tasks}), 200
		else :
			return jsonify({"message" : "tasks found", "tasks" : tasks}), 200
def deactivate_engineer_task():
    params = request.json
    engineer_id = params.get('engineer_id')
    deactivate_status = params.get('deactivate_status')
    cookies = request.cookies
    user_id = cookies.get('user_id')
    token = cookies.get('token')

    admin_obj = engineer_collection.find_one(
        {
            "id": user_id,
            "secret_hash": token,
            "is_admin": True
        }, {"_id": 0})

    if admin_obj:
        if deactivate_status:
            task_obj = task_collection.find(
                {
                    "assigned_user_id": engineer_id,
                    "task_status": {
                        "$in": ['completed', 'assigned']
                    }
                }, {"_id": 0})
            if task_obj.count() > 0:

                for task in task_obj:
                    task_collection.update_one({'id': task.get('id')}, {
                        "$set": {
                            "task_status": "unassigned",
                            "updated_at": str(datetime.datetime.now())
                        }
                    })

                result_obj = engineer_collection.update_one(
                    {'id': engineer_id}, {
                        "$set": {
                            "is_active": False,
                            "updated_at": str(datetime.datetime.now())
                        }
                    })
                resp = {
                    "message":
                    "Engineer deaactivated, {} marked as unassigned .. ".
                    format(task_obj.count())
                }
                return jsonify(resp), 200

            else:
                result_obj = engineer_collection.update_one(
                    {'id': engineer_id}, {
                        "$set": {
                            "is_active": False,
                            "updated_at": str(datetime.datetime.now())
                        }
                    })
                resp = {"message": "Engineer deactivated"}
                return jsonify(resp), 200

        else:
            task_obj = task_collection.find(
                {
                    "assigned_user_id": engineer_id,
                    "task_status": {
                        "$in": ['completed', 'assigned']
                    }
                }, {"_id": 0})
            print("----- tasks found ----{}".format(task_obj.count()))
            if task_obj:

                tasks = [t for t in task_obj]
                resp = {
                    "message": "tasks found",
                    "tasks": tasks,
                    "tasks_found": True
                }
                return jsonify(resp), 200
            else:
                resp = {"message": "tasks found", "tasks_found": False}
                return jsonify(resp), 200

    else:
        resp = {"message": "Invalid request"}
        return jsonify(resp), 404
def task_datetime():
    result = []
    param = {}
    param = request.json
    if param is not None:
        if "schedule_date" not in param:
            param = {}
            param['schedule_date'] = datetime.datetime.today().strftime(
                '%d-%m-%Y')

    if param is None:
        param = {}
        param['schedule_date'] = datetime.datetime.today().strftime('%d-%m-%Y')

    engineer_obj = engineer_collection.find(
        {
            "is_admin": False,
            "is_active": True
        }, {
            "id": 1,
            "name": 1,
            "phone": 1,
            "_id": 0
        })

    for e in engineer_obj:
        result_obj = {}
        todays_tasks = task_collection.find({
            "schedule_date":
            param['schedule_date'],
            "task_status": {
                "$ne": "assigned"
            },
            "assigned_user_id":
            e.get("id")
        }).count()
        result_obj['todays_tasks'] = todays_tasks

        todays_tasks = task_collection.find({
            "schedule_date":
            param['schedule_date'],
            "assigned_user_id":
            e.get("id")
        }).count()
        result_obj['todays_total_tasks'] = todays_tasks

        total_tasks = task_collection.find({
            "assigned_user_id": e.get("id"),
            "task_status": "assigned"
        }).count()
        result_obj['total_tasks'] = total_tasks

        location_obj = list(
            location_collection.find({
                "engineer_id": e.get("id")
            }, {
                "_id": 0
            }).sort([("created_at", -1)]).limit(1))

        e["tasks_info"] = result_obj
        e["name"] = e.get("name")
        e["phone"] = e.get("phone")

        if len(location_obj) != 0:
            e['location'] = {}
            e["location"] = location_obj[0]

            created_at_time = datetime.datetime.strptime(
                location_obj[0].get('created_at'), "%Y-%m-%d %H:%M:%S.%f")

            dif = datetime.datetime.now() - created_at_time

            if dif.total_seconds() > 900:
                e["location_status"] = "inactive"
            else:
                e["location_status"] = "active"
            # print(datetime.datetime.now())-location_obj[0].get('created_at'))
        else:
            e["location_status"] = "non_active"
            e['location'] = {"created_at": "2016-11-22 20:40:55.136679"}

        result.append(e)

    resp = {"message": "sucessfully got data", "list": result}

    return jsonify(resp), 200