package com.vogella.jersey.first.util;

import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.gte;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.google.gson.Gson;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.vogella.jersey.first.model.ChatMessage;
import com.vogella.jersey.first.model.mapobject.Coin;
import com.vogella.jersey.first.model.mapobject.MapObject;

public class ChatManager{

	private final MongoCollection<Document> collection;
	private final MongoClient mongoClient;
	protected final Random random;

	public static final String COLLECTION_NAME = "chat";

	public ChatManager(MongoClient mongoClient,MongoCollection<Document> collection){
		this.mongoClient = mongoClient;
		this.collection = collection;
		this.random = new Random();
	}

	private static MongoCollection<Document> retrieveCollection(MongoClient mongoClient){
		try{
			return mongoClient.getDatabase(GameMongoDBUtils.DATABASE_NAME).getCollection(COLLECTION_NAME);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return null;
	}

	public ChatMessage insert(ChatMessage mapObject){
		if(mapObject != null){
			synchronized(this){
				mapObject.id = getNewId();
				T mapObjectDB = get(mapObject.id);
				if(mapObjectDB == null){
					try{
						getCollection().insertOne(mapObject.getDocument());
						return mapObject;
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			}
		}
		return null;
	}
	
	public List<ChatMessage> getByType(int type){
		deleteOldMessages(type);
		List<ChatMessage> chatMessages = new ArrayList<>();
		Gson gson = new Gson();
		FindIterable<Document> listDoc = null;
		try{
			listDoc = collection.find(eq("type",type));
			if(listDoc != null){
				MongoCursor<Document> cursor = listDoc.iterator();
				try{
					ChatMessage mapObject;
					while(cursor.hasNext()){
						mapObject = gson.fromJson(cursor.next().toJson(),ChatMessage.class);
						if(mapObject != null){
							chatMessages.add(mapObject);
						}
					}
					return chatMessages;
				}finally{
					try{
						cursor.close();
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	private void deleteOldMessages(int type){
		
	}

	public String getNewId(){
		String id = System.currentTimeMillis() + "," + System.nanoTime();
		T mapObject = get(id);
		while(mapObject != null){
			id = System.currentTimeMillis() + "," + System.nanoTime();
			mapObject = get(id);
		}
		return id;
	}

}