from datetime import datetime, timedelta
import yt.wrapper as yt_wrapper
from datacloud.config import yt as yt_path
from datacloud.dev_utils.logging.logger import get_basic_logger
from datacloud.dev_utils.time.patterns import FMT_DATE_HM, FMT_DATE
from datacloud.dev_utils.time.utils import assert_date_str
from datacloud.dev_utils.yt import yt_utils
from datacloud.config.yt import YT_PROXY


logger = get_basic_logger(__name__)

TABLES_TO_SNAPSHOT = [
    yt_wrapper.ypath_join(yt_path.CRYPTA_DB_LAST_FOLDER, 'yuid_to_cid'),
    yt_wrapper.ypath_join(yt_path.CRYPTA_DB_LAST_FOLDER, 'email_id_value_to_cid'),
    yt_wrapper.ypath_join(yt_path.CRYPTA_DB_LAST_FOLDER, 'phone_id_value_to_cid'),
    yt_wrapper.ypath_join(yt_path.CRYPTA_DB_LAST_FOLDER, 'cid_to_all')
]


def detect_ready(date_time):
    yt_wrapper.config.set_proxy(YT_PROXY)
    date_time = datetime.strptime(date_time, FMT_DATE_HM)
    days = 5
    for min_diff in xrange(days):
        time_to_check = date_time - timedelta(days=min_diff)
        logger.info(' Check day: {}'.format(time_to_check))
        if time_to_check.weekday() != 1:  # Tuesday
            logger.info(' Skip {}, not Thirsday'.format(time_to_check))
            continue
        date_str = time_to_check.strftime(FMT_DATE)
        yield date_str, {'date_str': date_str}
        break


def _take_snapshot(yt_client, input_tables, output_snapshot_folder):
    with yt_client.Transaction():
        if not yt_client.exists(output_snapshot_folder):
            yt_utils.create_folders([output_snapshot_folder], yt_client)
        for table in input_tables:
            table_name = table.split('/')[-1]
            destination_path = yt_wrapper.ypath_join(output_snapshot_folder, table_name)
            logger.info('COPY TABLE {} => {}'.format(table, destination_path))
            yt_client.copy(table, destination_path)


def take_crypta_snapshot(task):
    date_str = task.data['date_str']
    assert_date_str(date_str)
    logger.info('START take_crypta_snapshot {}'.format(date_str))
    yt_client = yt_utils.get_yt_client()
    snapshot_folder = yt_wrapper.ypath_join(yt_path.CRYPTA_SNAPSHOT_FOLDER, date_str)
    _take_snapshot(yt_client, TABLES_TO_SNAPSHOT, snapshot_folder)
    logger.info('DONE take_crypta_snapshot {}'.format(date_str))
    return [task.make_done()]
