# Imports the Google Cloud client library
from google.cloud import datastore


class Datastore(object):
    def __init__(self, project_id=None):
        self.client = datastore.Client(project=project_id)

    def put_new_entity(self, kind, prop_df, name=None):
        # The Cloud Datastore key for the new entity
        if name is None:
            task_key = self.client.key(kind)
        else:
            task_key = self.client.key(kind, name)
        entity = datastore.Entity(key=task_key)
        for i in prop_df:
            entity[i] = prop_df[i]
        self.client.put(entity)

    def delete_entity(self, kind, name):
        key = self.client.key(kind, name)
        self.client.delete(key)

    def get_entity(self, kind, name):
        key = self.client.key(kind, name)
        return self.client.get(key=key)

    def query(self, kind, filter):
        query = self.client.query(kind=kind)
        if isinstance(filter[0], list) is False:
            filter = [filter]
        for item in filter:
            query.add_filter(item[0], item[1], item[2])
        result = query.fetch()
        res = result.pages
        results = []
        for i in list(res):
            for j in i:
                results.append(j)
        return results

    def update_entity(self, kind, name, prop_df):
        self.put_new_entity(kind, prop_df, name)

    def get_all_of_a_kind(self, kind):
        query = self.client.query(kind=kind)
        result = query.fetch()
        res = result.pages
        results = []
        for i in list(res):
            for j in i:
                results.append(j)
        return results





if __name__ == '__main__':

    # Examples:
    ds_handler = Datastore()
    ''' 
    # Create new entity on Datastore:
    
    kind = "TestKind1"
    data = {
        "property1": 1,
        "property2": "Property Number 2",
        "property3": 3.33
    }
    name = "TestName or ID"  # if None -> autogenerated from Google
    # ds_handler.put_new_entity(kind=kind, prop_df=data, name=name)

    # Delete Entity:
    # ds_handler.delete_entity(kind="TestKind1", name="TestName or ID")

    # Get Entity from Datastore:
    # entity = ds_handler.get_entity(kind="TestKind1", name="TestName or ID")
    # print(entity)

    # Query datastore:
    with_one_filter = ["property1", "=", 1]
    with_more_filter = [with_one_filter, ["property3", "<=", 3.33]]
    result = ds_handler.query(kind="TestKind1", filter=with_more_filter)
    print(result)


    # Update Entity:
    data = {
        "property1": 0,
        "property2": "Property Number 2",
        "property3": 333,
        "property4": 4
    }
    # ds_handler.update_entity(kind="TestKind1", name="TestName", prop_df=data)
    '''