from libs import mdswrapper
from uuid import uuid4
from datetime import datetime, timedelta
from stocks3.share.singleton import Singleton
from stocks3.core.config import JSONConfigurable
import os

NAMESPACE = 'stocks'
FILENAME_TEMPLATE = '{uuid}_{basename}'


class MdsClientHelper(JSONConfigurable, metaclass=Singleton):
    def __init__(self):
        JSONConfigurable.__init__(self)
        environment = self.read_item(['env']) or 'production'
        self.mdsclient = mdswrapper.MdsClient(NAMESPACE, env=environment)


stocks_mdsclient = MdsClientHelper()


def upload(graph_filename, filename=None):
    unique_part = str(uuid4())
    with open(graph_filename, 'rb') as graph:
        data = graph.read()
    if filename is None:
        filename = FILENAME_TEMPLATE.format(uuid=unique_part, basename=os.path.basename(graph_filename))

    try:
        return stocks_mdsclient.mdsclient\
            .write(filename, data, (datetime.now() + timedelta(days=25)).strftime("%Y%m%dT%H%M%SZ"))
    except mdswrapper.MdsError as mdse:
        return 'Some exception in MDS upload: {0}'.format(str(mdse))
