import datetime
import yt.wrapper as yt

import datacloud.crypta_utils.make_join_tables_v2 as mj_v2
from datacloud.dev_utils.time.patterns import FMT_DATE
from datacloud.dev_utils.time.utils import now_str
from datacloud.dev_utils.status_db.task import Task, Status
from datacloud.dev_utils.yt import yt_utils
from datacloud.stability.crypta_stability.constants import CRYPTA_DB_Q, CRYPTA_DB_LAST


def parse_yt_datetime(date_str):
    return datetime.datetime.strptime(date_str.split('T')[0], FMT_DATE)


def if_new_crypta_db(_, __=None):
    local_db_time = parse_yt_datetime(yt.get_attribute(
        yt.ypath_join(CRYPTA_DB_LAST, 'cid_to_all'),
        'modification_time'))
    if len(yt.list(CRYPTA_DB_Q)) > 0:
        q_db_time = parse_yt_datetime(yt.get_attribute(
            yt.ypath_join(CRYPTA_DB_Q, 'cid_to_all'),
            'modification_time'))
        local_db_time = max(local_db_time, q_db_time)

    is_new = False
    for table in mj_v2.input_crypta_tables:
        crypta_db_time = parse_yt_datetime(yt.get_attribute(
            table,
            'modification_time'
        ))
        days_diff = (crypta_db_time - local_db_time).days
        if days_diff > 0:
            is_new = True
            break
    print('Days diff between xprod and crypta: {}'.format(days_diff))
    if is_new:
        date_str = crypta_db_time.strftime(FMT_DATE)
        yield date_str, {'date_str': date_str}


def update_crypta_v2_join_tables(task):
    yt_client = yt_utils.get_yt_client()
    mj_v2.make_join_tables(yt_client, mj_v2.CryptaExtractTablesV2(
        base_root='//home/x-products/production',
        sub_folder='/crypta_v2/crypta_db_quarantine'
    ))

    current_time = now_str()
    date_str = task.data['date_str']
    return [
        task.make_done(),
        Task('check_crypta_stability', date_str, Status.READY, {'date_str': date_str}, current_time, current_time)
    ]
