# -*- coding: utf-8 -*-
import os
import uuid
from sklearn.externals import joblib
from datacloud.dev_utils.logging.logger import get_basic_logger

logger = get_basic_logger(__name__)


__all__ = [
    'upload_file',
    'download_file',
    'joblib_load_from_yt'
]


def upload_file(yt_client, local_path, yt_path, placement_strategy='ignore'):
    logger.info(' Upload file from {} to {}'.format(local_path, yt_path))
    yt_client.smart_upload_file(
        local_path,
        destination=yt_path,
        placement_strategy=placement_strategy)


def download_file(yt_client, yt_path, local_path, mode='w+'):
    logger.info(' Downlad file from {} to {}'.format(yt_path, local_path))
    with open(local_path, mode) as fh:
        fh.write(yt_client.read_file(yt_path).read())


def joblib_load_from_yt(yt_client, yt_path):
    logger.info(' Load with joblib from {}'.format(yt_path))
    local_filename = os.path.join('/tmp', uuid.uuid4().hex)
    download_file(yt_client, yt_path, local_filename, 'w+')
    obj = joblib.load(local_filename)
    os.remove(local_filename)
    return obj
