from graph import Graph
import json
import os

class Stats(Graph):
    def __init__(self):
        super().__init__('stats')
        self.data = { # general statistics in text form
            'start': None,
            'end': None,
            'http': {
                'count': 0,
                'size': 0,
                'unique': set(),
            },
            'ftp': {
                'count': 0,
                'size': 0,
                'unique': set(),
            },
            'totalUnique': set(),
        }

    def process(self, ip, time, request, size, location, log):
        # technically inefficient but this is much easier than handling every edge case of start/end not defined, multi files, etc
        if self.data['start'] == None or time < self.data['start']:
            self.data['start'] = time
        if self.data['end'] == None or time > self.data['end']:
            self.data['end'] = time

        if log == 'Apache':
            self.data['http']['count'] += 1
            self.data['http']['size'] += size
            self.data['http']['unique'].add(ip)
        elif log == 'FTP':
            self.data['ftp']['count'] += 1
            self.data['ftp']['size'] += size
            self.data['ftp']['unique'].add(ip)
        
        self.data['totalUnique'].add(ip)
        
        return []

    def draw(self, path):
        print('Writing statistics...')

        # these are used for downloadStats.php to display various text data
        out = {
            'start': self.data['start'].strftime('%m/%d/%Y'),
            'end': self.data['end'].strftime('%m/%d/%Y'),
            'http': {
                'count': self.data['http']['count'],
                'size': self.data['http']['size'],
                'unique': len(self.data['http']['unique']),
            },
            'ftp': {
                'count': self.data['ftp']['count'],
                'size': self.data['ftp']['size'],
                'unique': len(self.data['ftp']['unique']),
            },
            'totalUnique': len(self.data['totalUnique'])
        }

        with open(os.path.join(path, 'data.json'), 'w') as f:
            f.write(json.dumps(out))
