from json import loads as json_loads
from json import dumps as json_dumps
from datetime import timedelta
from redis import Redis
from app.library.market import get_market_data
from app.library.crypto import wow_wallet, xmr_wallet
from app import config


class Cache(object):
    def __init__(self):
        self.redis = Redis(host=config.REDIS_HOST, port=config.REDIS_PORT)

    def store_data(self, item_name, expiration_minutes, data):
        self.redis.setex(
            item_name,
            timedelta(minutes=expiration_minutes),
            value=data
        )

    def get_coin_price(self, coin_name):
        key_name = f'{coin_name}_price'
        data = self.redis.get(key_name)
        if data:
            return json_loads(data)
        else:
            d = get_market_data(coin_name)
            data = {
                key_name: d['market_data']['current_price'],
            }
            self.store_data(key_name, 4, json_dumps(data))
            return data

    # todo - remove if statement, pass swap object and determine from model logic
    def get_transfer_data(self, coin, subaddress_index):
        key_name = f'{coin}_wallet_{subaddress_index}_txes'
        data = self.redis.get(key_name)
        if data:
            return json_loads(data)
        else:
            if coin == 'wow':
                data = wow_wallet.get_transfers(subaddress_index)
            else:
                data = xmr_wallet.get_transfers(subaddress_index)
            self.store_data(key_name, 2, json_dumps(data))
            return data

cache = Cache()
