# By: Riasat Ullah
# This file contains functions to validate strings.

import datetime
import re


def is_date(text):
    '''
    Checks if the string is a valid date or not.
    All dates should be in these formats:
        1. YYYYMMDD
        2. YYYY-MM-DD
        3. YYYY/MM/DD
    :return: (boolean) True if it is; False otherwise
    '''
    pattern = '^[0-9]{4}[-/]{0,1}[0-9]{2}[-/]{0,1}[0-9]{2}$'
    hyphen = '-'
    backslash = '/'
    if re.match(pattern, text):
        date_text = text
        if hyphen in date_text:
            date_text = date_text.replace(hyphen, '')
        elif backslash in date_text:
            date_text = date_text.replace(backslash, '')
        if len(date_text) == 8:
            try:
                datetime.datetime.strptime(date_text, '%Y%m%d')
                return True
            except ValueError:
                return False
    return False


def is_timestamp(text):
    '''
    Checks if the string is a valid timestamp or not.
    :return: (boolean) True if it is; False otherwise
    '''
    pattern = '^[0-9]{4}[-/]{0,1}[0-9]{2}[-/]{0,1}[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$'
    hyphen = '-'
    backslash = '/'
    if re.match(pattern, text):
        timestamp_text = text
        if hyphen in timestamp_text:
            timestamp_text = timestamp_text.replace(hyphen, timestamp_text)
        elif backslash in timestamp_text:
            timestamp_text = timestamp_text.replace(backslash, timestamp_text)
        if len(timestamp_text) == 8:
            try:
                datetime.datetime.strptime(timestamp_text, '%Y%m%d %H:%M:%S')
                return True
            except ValueError:
                return False
    return False


def is_timestamp_with_milliseconds(text):
    '''
    Checks if the string is a valid json timestamp with milliseconds or not.
    '''
    pattern_milli = '^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]+$'
    if re.match(pattern_milli, text):
        return True
    return False


def is_json_timestamp(text):
    '''
    Checks if the string is a valid json timestamp or not.
    '''
    pattern = '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}$'
    if re.match(pattern, text):
        return True
    return False


def is_json_timestamp_with_milliseconds(text):
    '''
    Checks if the string is a valid json timestamp with milliseconds or not.
    '''
    pattern_milli = '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]+$'
    if re.match(pattern_milli, text):
        return True
    return False
