#!/usr/bin/python
# coding=utf-8

import sys

from peewee import Model, CharField, IntegerField, DateTimeField, PostgresqlDatabase, CompositeKey
from datetime import datetime
from dateutil.tz import tzlocal

# Leading underscore, denoting module private variable, may exclude this variable from wildcard imports on some versions of python
_database = PostgresqlDatabase('stop', user='stop', password='PT52lRecp4NBKQrZT9', host='database')

# Helper functions
def truncateString(value, size):
    valLen = len(value)
    if size <= 3 or valLen <= 3:
        return value

    return (value[:(size-3)] + '...') if valLen > size else value

# NOTE: most docker images run in UTC by default
def currentTime(format = None):
    ts = datetime.now(tzlocal())
    if not format:
        return ts

    return ts.strftime(format)

# PostgreSQL table classes:
class UnknownField(object):
    def __init__(self, *_, **__): pass

class BaseModel(Model):
    class Meta:
        database = _database

class GenderStats(BaseModel):
    rowid = IntegerField()
    t = CharField(column_name='t_id', max_length=10)
    t_ts = DateTimeField(default=currentTime)
    gender_text = CharField(null=True, max_length=100)

    class Meta:
        table_name = 'gender_stats'
        indexes = (
            (('t', 't_ts', 'rowid'), True),
        )
        primary_key = CompositeKey('rowid', 't', 't_ts')

def connect():
    if _database.is_closed():
        _database.connect()
    return _database

def close(db):
    if not db.is_closed():
        db.close()

def addStats(data, stopCode = None):
    stopCode = stopCode if stopCode else 'unknown'

    with _database.atomic():
        i = 0
        ts = currentTime() # only one value for current time per request
        for face in data:
            if not face['gender']:
                face['gender'] = 'unknown'

            GenderStats.create(
                t = truncateString(stopCode, GenderStats.t.max_length),
                t_ts = ts,
                rowid = i,
                gender_text = truncateString(face['gender'], GenderStats.gender_text.max_length)
            )

            # NOTE: having serial id here has low risk of PK collision iff parallel processing of requests is used.
            # Can be done f.ex. through multiple uwsgi workers, which the current setup does not use
            i += 1

def main(argv):
    db = connect()

    # create database tables
    if not GenderStats.table_exists():
        GenderStats.create_table()
        print("Created table: {0}".format(GenderStats.Meta.table_name))

    print("Database successfully initalized...")
    close(db)

    return True

if __name__ == "__main__":
    main(sys.argv)
