# -*- coding: utf-8 -*-
from django.db.models import Aggregate
from django.db.models.aggregates import Aggregate as SqlAggregate
from events.common_app.fields import JSONField


class Left(Aggregate):
    name = 'LEFT'

    def add_to_query(self, query, alias, col, source, is_summary):
        klass = SqlLeft
        aggregate = klass(col, source=source, is_summary=is_summary, **self.extra)
        query.aggregates[alias] = aggregate


json_aggregate_field = JSONField()


class SqlLeft(SqlAggregate):
    sql_function = 'LEFT'
    sql_template = '%(function)s(%(field)s,%(length)s)'

    def __init__(self, col, length, source=None, **extra):
        super(SqlLeft, self).__init__(col, length=length, source=json_aggregate_field, **extra)
