import os
import yt.wrapper as yt_wrapper
from datacloud.dev_utils.logging.logger import get_basic_logger
from datacloud.config.yt import STATUS_DB_TABLE
from datacloud.dev_utils.yt import yt_utils
from datacloud.dev_utils.yql import yql_helpers


logger = get_basic_logger(__name__)

view_table = '//home/x-products/public/view/status-db-view'


query = """
pragma yt.QueryCacheMode = 'refresh';
pragma yt.QueryCacheIgnoreTableRevision = 'true';
$parser = DateTime::Parse("%Y-%m-%d %H:%M:%S");

INSERT INTO `{view_table}` WITH TRUNCATE
SELECT
  status, program, key, update_time
FROM
`{status_db_table}`
WHERE status == 'READY'
OR CurrentUtcDatetime() + DateTime::IntervalFromHours(3) - DateTime::IntervalFromMinutes(15) < DateTime::MakeDatetime($parser(update_time));
"""


def create_status_db_view():
    logger.info('Start create status-db view')
    yql_token = yt_wrapper.config['token'] or os.environ.get('YQL_TOKEN', '')
    yql_client = yql_helpers.create_yql_client(yt_utils.get_yt_client(), token=yql_token)
    yql_helpers.execute_yql(
        query.format(status_db_table=STATUS_DB_TABLE, view_table=view_table),
        yql_client=yql_client,
        syntax_version=1)
    logger.info('Done {}'.format(view_table))
