#! /usr/bin/env python
__author__ = "Ben Raanan"
__copyright__ = "Copyright 2021, MBARI"
__credits__ = ["MBARI"]
__license__ = "GPL-3.0"
__maintainer__ = "Ben Raanan"
__email__ = "byraanan at mbari.org"
__doc__ = '''

Defines the CsvWriter class as part of the LRAUV—bioacoustics backseat application. 

@author: __author__
@license: __license__
'''
import csv
import logging
import os
from datetime import datetime, timedelta

logger = logging.getLogger("backseat")


class CsvWriter:

    def __init__(self, name: str, log_base: str, headers: list, max_log_duration_hr: int, max_log_size_mb=25):
        self.max_log_duration_hr = timedelta(hours=max_log_duration_hr)
        self.max_log_size_bytes = max_log_size_mb * (1024*1024.0)
        self.log_base = log_base
        self.headers = headers
        self.name = name

        self.log_path = ""
        self.log_name = ""
        self.log_time = None
        self.log_rotate_time = None

        # logger.info(f'CSV log duration set to: {self.max_log_duration_hr}')
        self.rotate_log()


    def file_size(self):
        return os.path.getsize(self.log_path)


    def write(self, data: list):
        with open(self.log_path, mode='a', newline='') as f:
            csv_writer = csv.writer(f, delimiter=',')
            csv_writer.writerow(data)

        self.check_log_duration_and_rotate()


    def rotate_log(self):
        self.log_time = datetime.now()
        self.log_rotate_time = self.log_time + self.max_log_duration_hr
        self.log_name = "{}_{}.csv".format(self.name, self.log_time.strftime('%Y%m%dT%H%M%S'))
        self.log_path = os.path.join(self.log_base, self.log_name)
        logger.info(f'Starting new CSV log: {self.log_name}')
        # logger.info(f'Next rotate at: {self.log_rotate_time}')
        self.write(self.headers)


    def check_log_duration_and_rotate(self):
        if datetime.now() >= self.log_rotate_time:
            self.rotate_log()


    def check_log_size_and_rotate(self):
        if self.file_size() >= self.max_log_size_bytes:
            self.rotate_log()

