import os
import logging
import datetime


logger = logging.getLogger(__name__)
START_SKIP_DIR_NAME = ['./.', './static', '/migrations']
END_SKIP_DIR_NAME = ['/migrations']
current_year = datetime.datetime.now().year
next_year = (datetime.datetime.now() + datetime.timedelta(days=365)).year
COPYRIGHTS_YEAR = f'Copyright {current_year}-{next_year}'
COPYRIGHTS_INFORMATION = '# ' + COPYRIGHTS_YEAR + ', BRDWT. All rights reserved.\n'


def check_valid_dir(name):
    """
    verifying the directory is valid or not from skip directory list
    :param name: str
    :return: boolean
    """
    for skip_dir in START_SKIP_DIR_NAME:
        if name.startswith(skip_dir):
            return False
    for skip_dir in END_SKIP_DIR_NAME:
        if name.endswith(skip_dir):
            return False
    return True


def check_valid_file(name):
    """
    verifying the file is valid or not from skip file
    :param name: str
    :return: boolean
    """
    if name.startswith('_'):
        return False
    if not (name.endswith('.py') or name.endswith('.yaml')):
        return False
    if name == 'manage.py' or name == 'appengine_config.py':
        return False
    return True


for dir_name, sub_dir_list, file_list in os.walk('..'):
    if check_valid_dir(dir_name):
        for file_name in file_list:
            if check_valid_file(file_name):
                full_path = os.path.join(dir_name, file_name)
                text = ''
                try:
                    with open(full_path) as f:
                        text = f.read()
                except IOError:
                    logger.debug('An error occurred trying to read the file : ' + full_path)

                if text is not None:
                    lines = text.splitlines() + ['']
                    COPYRIGHTS_INFORMATION_exist = False

                    # searching for copyrights information up to 5 or the
                    # length of line number in files.
                    for i in range(0, min(5, len(lines))):
                        try:
                            if 'Copyright' in lines[i]:
                                COPYRIGHTS_INFORMATION_exist = True
                                # updating the copy rights year if it is
                                # outdated
                                if COPYRIGHTS_YEAR not in lines[i]:
                                    lines[i] = COPYRIGHTS_INFORMATION
                                    break
                        except IndexError:
                            logging.debug('Index out of range on : ' + str(i))
                            break

                    # copyrights information is added to list, if it is not
                    # found
                    if not COPYRIGHTS_INFORMATION_exist:
                        lines = [COPYRIGHTS_INFORMATION] + lines
                    try:
                        # Writing the updated file with copyrights information
                        with open(full_path, 'w') as op:
                            op.write('\n'.join(lines))
                    except IOError:
                        logger.debug('An error occurred trying to write the file : ' + full_path)
