import csv
import os
from datetime import datetime


class CSVExporter():

    @staticmethod
    def find_first_empty_row(file_path):
        if not os.path.exists(file_path):
            return 1
        with open(file_path, newline='', encoding='utf-8') as csvfile:
            return sum(1 for _ in csvfile) + 1

    def push_array(self, array_of_array, file_path=None):
        if file_path == None:
            file_path = str(datetime.now().strftime('%Y_%m_%d_%H_%M_%S'))+".csv"
        mode = 'a' if os.path.exists(file_path) else 'w'
        with open(file_path, mode, newline='', encoding='utf-8') as csvfile:
            writer = csv.writer(csvfile)
            for row in array_of_array:
                writer.writerow(row)

    def push_line(self, array, file_path=None):
        if file_path == None:
            file_path = str(datetime.now().strftime('%Y_%m_%d_%H_%M_%S'))+".csv"
        self.push_array([array], file_path)

    def push_column(self, array, file_path=None):
        if file_path == None:
            file_path = str(datetime.now().strftime('%Y_%m_%d_%H_%M_%S'))+".csv"
        temp = [[item] for item in array]
        self.push_array(temp, file_path)
    
    def push_array_under_column_one(self, column, file_path=None):
        if file_path == None:
            file_path = str(datetime.now().strftime('%Y_%m_%d_%H_%M_%S'))+".csv"
        existing_rows = []
        if os.path.exists(file_path):
            with open(file_path, newline='', encoding='utf-8') as csvfile:
                reader = list(csv.reader(csvfile))
                existing_rows = reader
        start_index = 0
        while start_index < len(existing_rows) and existing_rows[start_index] and existing_rows[start_index][0].strip() != '':
            start_index += 1
        for i, value in enumerate(column):
            row_index = start_index + i
            if row_index < len(existing_rows):
                while len(existing_rows[row_index]) < 1:
                    existing_rows[row_index].append('')
                existing_rows[row_index][0] = value
            else:
                existing_rows.append([value])
        with open(file_path, 'w', newline='', encoding='utf-8') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerows(existing_rows)

if __name__ == "__main__":
    CSVExporter().push_array_under_column_one(["d","e","f"],"test.csv")
