# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Base model class."""

from core.platform import models
import utils

from google.appengine.datastore import datastore_query
from google.appengine.ext import ndb

transaction_services = models.Registry.import_transaction_services()

# The delimiter used to separate the version number from the model instance
# id. To get the instance id from a snapshot id, use Python's rfind()
# method to find the location of this delimiter.
_VERSION_DELIMITER = '-'

# Constants used for generating ids.
MAX_RETRIES = 10
RAND_RANGE = 127 * 127
ID_LENGTH = 12


class BaseModel(ndb.Model):
    """Base model for all persistent object storage classes."""

    # When this entity was first created. This can be overwritten and
    # set explicitly.
    created_on = ndb.DateTimeProperty(auto_now_add=True, indexed=True)
    # When this entity was last updated. This cannot be set directly.
    last_updated = ndb.DateTimeProperty(auto_now=True, indexed=True)
    # Whether the current version of the model instance is deleted.
    deleted = ndb.BooleanProperty(indexed=True, default=False)

    @property
    def id(self):
        """A unique id for this model instance."""
        return self.key.id()

    def _pre_put_hook(self):
        """This is run before model instances are saved to the datastore.

        Subclasses of BaseModel should override this method.
        """
        pass

    class EntityNotFoundError(Exception):
        """Raised when no entity for a given id exists in the datastore."""
        pass

    @classmethod
    def get(cls, entity_id, strict=True):
        """Gets an entity by id. Fails noisily if strict == True.

        Args:
          entity_id: str. The id of the entity.
          strict: bool. Whether to fail noisily if no entity with the given id
            exists in the datastore.

        Returns:
          None, if strict == False and no undeleted entity with the given id
          exists in the datastore. Otherwise, the entity instance that
          corresponds to the given id.

        Raises:
        - base_models.BaseModel.EntityNotFoundError: if strict == True and
            no undeleted entity with the given id exists in the datastore.
        """
        entity = cls.get_by_id(entity_id)
        if entity and entity.deleted:
            entity = None

        if strict and entity is None:
            raise cls.EntityNotFoundError(
                'Entity for class %s with id %s not found' %
                (cls.__name__, entity_id))
        return entity

    def put(self):
        super(BaseModel, self).put()

    @classmethod
    def get_multi(cls, entity_ids, include_deleted=False):
        """Returns a list, each entry of which is the instance model
        corresponding to the entity_id, except for the following two cases (in
        which the corresponding entry is None instead):
          - the instance is not found
          - the instance has been deleted, and `include_deleted` is True.
        """
        entity_keys = [ndb.Key(cls, entity_id) for entity_id in entity_ids]
        entities = ndb.get_multi(entity_keys)
        if not include_deleted:
            for i in xrange(len(entities)):
                if entities[i] and entities[i].deleted:
                    entities[i] = None
        return entities

    @classmethod
    def put_multi(cls, entities):
        return ndb.put_multi(entities)

    def delete(self):
        super(BaseModel, self).key.delete()

    @classmethod
    def get_all(cls, include_deleted_entities=False):
        """Returns a filterable iterable of all entities of this class.

        If include_deleted_entities is True then entities that have been marked
        deleted are returned as well.
        """
        query = cls.query()
        if not include_deleted_entities:
            query = query.filter(cls.deleted == False)  # pylint: disable=singleton-comparison
        return query

    @classmethod
    def get_new_id(cls, entity_name):