import re
from datacloud.dev_utils.logging.logger import get_basic_logger
from datacloud.dev_utils.time.patterns import RE_DAILY_LOG_FORMAT

logger = get_basic_logger(__name__)


def _validate_filename(filename):
    max_filename_length = 50
    parts = filename.split('.')
    if len(parts) != 2:
        logger.warn('Wrong filename {}'.format(filename))
        return False
    name, extention = parts
    if extention != 'csv':
        logger.warn('Wrong extention {}'.format(filename))
        return False
    if not re.match(RE_DAILY_LOG_FORMAT, name[:10]):
        logger.warn('Wrong date-prefix in filename {}'.format(filename))
        return False
    if len(filename) > max_filename_length:
        logger.warn('Too long filename {}'.format(filename))
        return False
    return True


class Trigger(object):
    pass


class NewFileTrigger(Trigger):

    def __call__(self, storage, storage_folder, old_items,
                 filename_validator=_validate_filename):
        logger.info('NewFileTrigger check {}'.format(storage_folder))
        # path = os.path.join(storage_root, 'input')
        for input_name in storage.list(storage_folder):
            if filename_validator(input_name) and input_name not in old_items:
                logger.info('New target found: {}'.format(input_name))
                yield input_name


class DateTrigger(Trigger):
    # TODO: Should check that new score is available and date > required_date
    pass
