from tEDataProj.settings import EXCEPTION_IMPORT_LOG_PATH, EXCEPTION_LOG_PATH
import codecs
from datetime import datetime

def open_log_file(message, filename=None, import_exc=False):

    if not filename:
        if import_exc:
            filename = u'import_errors.log'
        else:
            filename = u'errors.log'

    if import_exc:
        path = EXCEPTION_IMPORT_LOG_PATH
    else:
        path = EXCEPTION_LOG_PATH

    f = codecs.open(path + filename, 'a', "utf-8")

    msg = u'{0} - {1}\n---------------------------\n\n'.format(
        str(datetime.now()),
        message
    )
    f.write(msg)

    return f


def close_log_file(f, message):

    msg = u'---------------------------\n{0} - {1}\n\n'.format(
        str(datetime.now()),
        message
    )
    f.write(msg)

    f.close()

    return True


def save_log_string(f, exc_data):

    msg = u'- {0} - {1} ({2})\n{3}\n'.format(
        str(datetime.now()),
        exc_data['err_code'],
        exc_data['err_text'],
        exc_data['err_data'],
    )


    f.write(msg)

    return True


def generate_error(f, err_code, err_text, err_data):

    exc_data = {
        'err_code' : err_code,
        'err_text' : err_text,
        'err_data' : err_data
    }

    save_log_string(f, exc_data)

    return exc_data