import json

from py_jftech import read, write, where, format_date

from api import AssetPoolType

__COLUMNS__ = {
    'rap_id': 'id',
    'rap_date': 'date',
    'rap_type': 'type',
    'rap_asset_ids': 'asset_ids',
}


@read
def get_list(max_date=None, min_date=None, type: AssetPoolType = None):
    sqls = []
    if max_date:
        sqls.append(f"rap_date <= '{format_date(max_date)}'")
    if min_date:
        sqls.append(f"rap_date >= '{format_date(min_date)}'")
    return f'''
    select {','.join([f"`{x[0]}` as `{x[1]}`" for x in __COLUMNS__.items()])} from robo_assets_pool
    {where(*sqls, rap_type=type)} order by rap_type, rap_date
    '''


@read(one=True)
def get_one(day, type: AssetPoolType):
    return f'''select {','.join([f"`{x[0]}` as `{x[1]}`" for x in __COLUMNS__.items()])} from robo_assets_pool {where(rap_date=day, rap_type=type)}'''


@read(one=True)
def get_last_one(type: AssetPoolType = None, day=None):
    sql = f"rap_date <= '{format_date(day)}'" if day else None
    return f'''select {','.join([f"`{x[0]}` as `{x[1]}`" for x in __COLUMNS__.items()])} from robo_assets_pool {where(sql, rap_type=type)} order by rap_date desc limit 1'''


@write
def insert(day, type: AssetPoolType, pool: list):
    return f'''
        insert into robo_assets_pool(rap_date, rap_type, rap_asset_ids)
        values ('{format_date(day)}', {type.value},'{json.dumps(pool)}')
    '''


@write
def delete(day=None):
    if day:
        return f"delete from robo_assets_pool where rap_date >= '{format_date(day)}'"
    else:
        return 'truncate table robo_assets_pool'
