# Path: app/errors.py
# class OperationFailure(pymongo.errors.OperationFailure):
#     def __init__(self, message):
#         super(OperationFailure, self).__init__(message)
#         self.message = "Can not complete operation on database. This could be a authentication error"
# 
# class GroupNameNotValid(Exception):
#     def __init__(self):
#         self.message = "Group name not valid. Should not empty or contains dots"
# 
# Path: app/errors.py
# class ConnectionFailure(pymongo.errors.ConnectionFailure):
#     def __init__(self, message):
#         super(ConnectionFailure, self).__init__(message)
#         self.message = "Can not connect to mongodb. Please check configuration"
#         self.status_code = 500
# 
# Path: app/errors.py
# class NotMasterError(pymongo.errors.NotMasterError):
#     def __init__(self, message):
#         super(NotMasterError, self).__init__(message)
#         self.message = "Can not write to database. Please wait until reconnected to master or start with proper configuration"
#         self.status_code = 500
# 
# Path: app/errors.py
# class ServiceNameNotValid(Exception):
#     def __init__(self):
#         self.message = "Service name not valid. Should not empty or contains dots"
# 
# Path: app/errors.py
# class ServiceAlreadyExists(Exception):
#     def __init__(self):
#         self.message = "Service with this name already exists"
# 
# Path: app/errors.py
# class NotFound(Exception):
#     def __init__(self):
#         self.message = "Service or Group not found"
#         self.status_code = 404
# 
# Path: app/errors.py
# class GateStateNotValid(Exception):
#     def __init__(self):
#         self.message = "state must be open or closed"
# 
# Path: app/errors.py
# class EnvironmentNotFound(Exception):
#     def __init__(self, environment):
#         self.message = "Environment " + environment + " not found."
#         self.status_code = 404
# 
# Path: app/errors.py
# class JsonStructureError(Exception):
#     def __init__(self, message=""):
#         self.message = "Your json contains invalid information. " + message


import uuid
import pymongo.errors
from pymongo import MongoClient
from delorean import Delorean
from datetime import timedelta, datetime
from app.errors import OperationFailure, GroupNameNotValid
from app.errors import ConnectionFailure
from app.errors import NotMasterError
from app.errors import ServiceNameNotValid
from app.errors import ServiceAlreadyExists
from app.errors import NotFound
from app.errors import GateStateNotValid
from app.errors import EnvironmentNotFound
from app.errors import JsonStructureError
                request['environments']) != list:
            raise JsonStructureError("Invalid environments.")
        try:
            data = dict()
            data['_id'] = str(uuid.uuid4())
            data['document_version'] = 2.2
            data['name'] = name.strip()
            data['group'] = group.strip()
            data['environments'] = self.get_environment_structure(request['environments'])

            self.collection.insert_one(data)
            data.pop('_id')  # do not return _id  
            return data
        except pymongo.errors.NotMasterError as error:
            raise NotMasterError(error.details)

    def remove_gate(self, group, name):
        if not self.check_existence(group, name):
            raise NotFound
        try:
            self.collection.remove({"name": name, "group": group})
        except pymongo.errors.NotMasterError as error:
            raise NotMasterError(error.details)

    def update_gate(self, group, name, entry):
        try:
            self.collection.update({"name": name, "group": group}, {'$set': entry}, upsert=False)
        except pymongo.errors.ConnectionFailure:
            raise ConnectionFailure("Connection failure while gate update")
        except pymongo.errors.OperationFailure as error:

# Path: app/errors.py
# class OperationFailure(pymongo.errors.OperationFailure):
#     def __init__(self, message):
#         super(OperationFailure, self).__init__(message)
#         self.message = "Can not complete operation on database. This could be a authentication error"
# 
# class GroupNameNotValid(Exception):
#     def __init__(self):
#         self.message = "Group name not valid. Should not empty or contains dots"
# 
# Path: app/errors.py
# class ConnectionFailure(pymongo.errors.ConnectionFailure):
#     def __init__(self, message):
#         super(ConnectionFailure, self).__init__(message)
#         self.message = "Can not connect to mongodb. Please check configuration"
#         self.status_code = 500
# 
# Path: app/errors.py
# class NotMasterError(pymongo.errors.NotMasterError):
#     def __init__(self, message):
#         super(NotMasterError, self).__init__(message)
#         self.message = "Can not write to database. Please wait until reconnected to master or start with proper configuration"
#         self.status_code = 500
# 
# Path: app/errors.py
# class ServiceNameNotValid(Exception):
#     def __init__(self):
#         self.message = "Service name not valid. Should not empty or contains dots"
# 
# Path: app/errors.py
# class ServiceAlreadyExists(Exception):
#     def __init__(self):
#         self.message = "Service with this name already exists"
# 
# Path: app/errors.py
# class NotFound(Exception):
#     def __init__(self):
#         self.message = "Service or Group not found"
#         self.status_code = 404
# 
# Path: app/errors.py
# class GateStateNotValid(Exception):
#     def __init__(self):
#         self.message = "state must be open or closed"
# 
# Path: app/errors.py
# class EnvironmentNotFound(Exception):
#     def __init__(self, environment):
#         self.message = "Environment " + environment + " not found."
#         self.status_code = 404
# 
# Path: app/errors.py
# class JsonStructureError(Exception):
#     def __init__(self, message=""):
#         self.message = "Your json contains invalid information. " + message


# Path: app/mongo_connect.py
import uuid
import pymongo.errors
from pymongo import MongoClient
from delorean import Delorean
from datetime import timedelta, datetime
from app.errors import OperationFailure, GroupNameNotValid
from app.errors import ConnectionFailure
from app.errors import NotMasterError
from app.errors import ServiceNameNotValid
from app.errors import ServiceAlreadyExists
from app.errors import NotFound
from app.errors import GateStateNotValid
from app.errors import EnvironmentNotFound
from app.errors import JsonStructureError

                request['environments']) != list:
            raise JsonStructureError("Invalid environments.")
        try:
            data = dict()
            data['_id'] = str(uuid.uuid4())
            data['document_version'] = 2.2
            data['name'] = name.strip()
            data['group'] = group.strip()
            data['environments'] = self.get_environment_structure(request['environments'])

            self.collection.insert_one(data)
            data.pop('_id')  # do not return _id  
            return data
        except pymongo.errors.NotMasterError as error:
            raise NotMasterError(error.details)

    def remove_gate(self, group, name):
        if not self.check_existence(group, name):
            raise NotFound
        try:
            self.collection.remove({"name": name, "group": group})
        except pymongo.errors.NotMasterError as error:
            raise NotMasterError(error.details)

    def update_gate(self, group, name, entry):
        try:
            self.collection.update({"name": name, "group": group}, {'$set': entry}, upsert=False)
        except pymongo.errors.ConnectionFailure:
            raise ConnectionFailure("Connection failure while gate update")
        except pymongo.errors.OperationFailure as error:

            raise OperationFailure(error.details)