<commit_before>"""
Class to read DBF files.
"""

import os
import datetime
import collections

from .struct_parser import StructParser
from .field_parser import FieldParser
from .common import parse_string
from .ifiles import ifind
from .fpt import FPT

DBFHeader = StructParser(
    'DBFHeader',
    '<BBBBLHHHBBLLLBBH',
    ['dbversion',
     'year',
     'month',
     'day',
     'numrecords',
     'headerlen',
     'recordlen',
     'reserved1',
     'incomplete_transaction',
     'encryption_flag',
     'free_record_thread',
     'reserved2',
     'reserved3',
     'mdx_flag',
     'language_driver',
     'reserved4',
     ])

DBFField = StructParser(
    'DBFField',
    '<11scLBBHBBBB7sB',
    ['name',
     'type',
     'address',
     'length',
     'decimal_count',
     'reserved1',
     'workarea_id',
     'reserved2',
     'reserved3',
     'set_fields_flag',
     'reserved4',
     'index_field_flag',
     ])

FieldValue = collections.namedtuple('Field', 'name value')


def flip_year(year):
    """
    Convert 2-digit year to 4-digit year, or 4-digit year to 2-digit year
    """
    
    if year > 100:
        # Convert 4-digit year to 2-digit
        if year < 2000:
            return year - 1900
        else:
            return year - 2000
    else:
        # Convert 2-digit year to 4-digit
        if year < 80:
            return 2000 + year
        else:
            return 1900 + year

class DBF(list):
    """
    Class to read DBF files.
    """

    def __init__(self, filename,
                 encoding='latin1',  # Todo: is this a good default?
                 raw=False,
                 ignorecase=True,
                 lowernames=False,
                 parserclass=FieldParser,
                 recfactory=dict,
                 peek=False):

        self.encoding = encoding
        self.recfactory = recfactory
        self.raw = raw
        self.ignorecase = ignorecase
        self.lowernames = lowernames
        self.parserclass = parserclass

        self._field_parser = self.parserclass(self.encoding)

        # Name part before .dbf is the table name
        self.name = os.path.basename(filename)
        self.name = os.path.splitext(self.name)[0]
        self.name = self.name.lower()

        if ignorecase:
            self.filename = ifind(filename)
        else:
            self.filename = filename

        # Filled in by self._read_headers()
        self.memofilename = None
        self.header = None
        self.fields = []       # namedtuples
        self.field_names = []  # strings

        with open(self.filename, mode='rb') as self.file:
            self._read_headers()
            self._check_headers()
            
            self.date = datetime.date(flip_year(self.header.year),
                                      self.header.month,
                                      self.header.day)
            
            self.deleted = []
            
            if not peek:
                self._load()

    def _read_headers(self):
        #
        # Todo: more checks
        # http://www.clicketyclick.dk/databases/xbase/format/dbf_check.html#CHECK_DBF
        #
        self.header = DBFHeader.read(self.file)<commit_msg>Changed flip_year() to less confusing expand_year().<commit_after>"""
Class to read DBF files.
"""

import os
import datetime
import collections

from .struct_parser import StructParser
from .field_parser import FieldParser
from .common import parse_string
from .ifiles import ifind
from .fpt import FPT

DBFHeader = StructParser(
    'DBFHeader',
    '<BBBBLHHHBBLLLBBH',
    ['dbversion',
     'year',
     'month',
     'day',
     'numrecords',
     'headerlen',
     'recordlen',
     'reserved1',
     'incomplete_transaction',
     'encryption_flag',
     'free_record_thread',
     'reserved2',
     'reserved3',
     'mdx_flag',
     'language_driver',
     'reserved4',
     ])

DBFField = StructParser(
    'DBFField',
    '<11scLBBHBBBB7sB',
    ['name',
     'type',
     'address',
     'length',
     'decimal_count',
     'reserved1',
     'workarea_id',
     'reserved2',
     'reserved3',
     'set_fields_flag',
     'reserved4',
     'index_field_flag',
     ])

FieldValue = collections.namedtuple('Field', 'name value')


def expand_year(year):
    """
    Convert 2-digit year to 4-digit year.
    """
    
    if year < 80:
        return 2000 + year
    else:
        return 1900 + year

class DBF(list):
    """
    Class to read DBF files.
    """

    def __init__(self, filename,
                 encoding='latin1',  # Todo: is this a good default?
                 raw=False,
                 ignorecase=True,
                 lowernames=False,
                 parserclass=FieldParser,
                 recfactory=dict,
                 peek=False):

        self.encoding = encoding
        self.recfactory = recfactory
        self.raw = raw
        self.ignorecase = ignorecase
        self.lowernames = lowernames
        self.parserclass = parserclass

        self._field_parser = self.parserclass(self.encoding)

        # Name part before .dbf is the table name
        self.name = os.path.basename(filename)
        self.name = os.path.splitext(self.name)[0]
        self.name = self.name.lower()

        if ignorecase:
            self.filename = ifind(filename)
        else:
            self.filename = filename

        # Filled in by self._read_headers()
        self.memofilename = None
        self.header = None
        self.fields = []       # namedtuples
        self.field_names = []  # strings

        with open(self.filename, mode='rb') as self.file:
            self._read_headers()
            self._check_headers()
            
            self.date = datetime.date(expand_year(self.header.year),
                                      self.header.month,
                                      self.header.day)
            
            self.deleted = []
            
            if not peek:
                self._load()

    def _read_headers(self):
        #
        # Todo: more checks
        # http://www.clicketyclick.dk/databases/xbase/format/dbf_check.html#CHECK_DBF
        #
        self.header = DBFHeader.read(self.file)
{'fraction_non_alphanumeric': 0.10413303196641911, 'fraction_numerical': 0.011462705844365515, 'mean_word_length': 1.7387267904509285, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1246852', 'n_tokens_mistral': 1900, 'n_tokens_neox': 1824, 'n_words': 402}