# -*- coding: utf-8 -*-
import pymongo
from pymongo import MongoClient
class Buffer:
	def __init__(self, col, bufCount, indexKey=None):
		self.bufCount = bufCount
		self.col = col
		self.buf = []
		self.indexKey = indexKey
		if indexKey: self.index = {}
	def flush(self):
		pass
	def write(self, rec):
		if self.indexKey:
			if rec[self.indexKey] in self.index: return
		self.buf.append(rec)
		if self.indexKey:
			self.index[rec[self.indexKey]] = True
		if(len(self.buf) > self.bufCount):
			self.flush()
	def fieldCheck(self, fieldName, value):
		value = value.lower().strip()
		for iter in self.buf:
			if iter[fieldName].lower().strip() == value: return True
		return False
	def geoFieldCheck(self, latClb, lonClb, lat, lon, fieldName, value, dist):
		value = value.lower().strip()
		for iter in self.buf:
			if iter[fieldName].lower().strip() == value:
				iLat = latClb(iter)
				iLon = latClb(iter)
				p1 = (lat, lon)
				p2 = (iLat, iLon)
				d = vincenty(p1, p2).m
				if d < dist: return True
		return False
		
	
	
class SaveBuffer(Buffer):
	def flush(self):
		if not self.buf: return
		
		self.col.insert(self.buf)
		self.buf = []

class UpdateBuffer(Buffer):
	def flush(self):
		if not self.buf: return
		
		bulk = self.col.initialize_unordered_bulk_op()
		for iter in self.buf:
			#self.col.update({'_id': iter['id']}, iter['toUpdate'])
			bulk.find({'_id': iter['id']}).update(iter['toUpdate'])
		bulk.execute()
