"""
module to define probe class
"""
from csv import reader, writer
from datetime import timedelta, datetime
from pandas import read_csv
from os.path import isfile
from os import remove
from sqlite3 import connect
from tools.my_logger import main_logger

class Probe:
    def __init__(self, file_path:str)->None:
        """
        constructor: store only one parameter: the path file of csv file
        :param file_path: str, the csv file
        """
        self.__file_path = file_path

    def __read(self)->list:
        """
        method for reading the csv file, and return list containing the reading
        :return: the list
        """
        if isfile(self.__file_path):
            #open the file
            with open(self.__file_path,'r',encoding='utf-8') as my_read_file:
                #create csv parser
                parser = reader(my_read_file, delimiter=',')
                #read all line
                for line in parser:
                    #control: only line with 7 columns !
                    if len(line) == 7:
                        #make generator using yield instruction
                        yield line

    def clean_and_save(self, file_path:str)->None:
        """
        clean csv file and save to the new path file
        :param file_path: the new file for storing csv cleand data
        :return: nothing. TODO: return code ;-)
        """
        #prepare the new file to be written
        with open(file_path, 'w', encoding='utf-8') as my_write_file:
            #make csv parser to write line
            parser_w = writer(my_write_file, delimiter=';', lineterminator='\n')
            #use the read method
            for line in self.__read():
                try:
                    #get the date
                    date = line[1]
                    #produce new date with one day added
                    #first: create datetime object (date object can be used)
                    date_obj:datetime = datetime.strptime(date,'%d/%m/%Y')
                    #add one day
                    date_obj = date_obj + timedelta(days=1)
                    #transform datetime object to string
                    date_str = date_obj.strftime('%Y-%m-%d')
                    #other way to call the method (same effect)
                    date_str = datetime.strftime(date_obj, '%Y-%m-%d')
                    #if we want to get day, month and year
                    day, month, year = date.split('/')
                    #two ways to change date, choose only one !
                    #change date order
                    line[1] = f'{year}-{month}-{day}'
                    #change date (add one day)
                    line[1] = date_str
                except Exception as error:
                    #the head line creates an exception: more efficient than a if instruction
                    # add pass instruction, or error in logger.
                    #main_logger.error(f"Error while treating csv line {error}")
                    pass
                #write part of the line
                parser_w.writerow(line[:3])

    def csv_to_sql(self, file_sql_path:str, file_csv_path:str)->None:
        """
        method to save data into sqlite3 database
        :param file_sql_path: file containing database
        :param file_csv_path: csv file (supposed to be cleaned !)
        :return: nothing
        """
        #using pandas csv reader
        data_set = read_csv(file_csv_path,delimiter=";")
        #if database exists, destroy it !
        if isfile(file_sql_path):
            remove(file_sql_path)
        #now, create new database
        with connect(file_sql_path) as my_db:
            #make cursor
            cursor = my_db.cursor()
            #create table
            cursor.execute("CREATE TABLE sonde (day integer, day_str text, max_temp real)")
            #add lines with only on instruction
            cursor.executemany("INSERT INTO sonde VALUES (?,?,?)", data_set.values.tolist())
            my_db.commit()

    def display_line(self, number_day:int, file_sql_path:str)->tuple[tuple]:
        """
        method for displaying data for one mission day
        :param number_day: type int, day of the mission
        :param file_sql_path: database file path
        :return: tuple of lines
        """
        #open database
        with connect(file_sql_path) as my_db:
            cursor = my_db.cursor()
            result = cursor.execute(f"SELECT * FROM sonde WHERE day={number_day};")
            #load all lines in memory; first result var is generator
            result = result.fetchall()
        #return result; database is closed a this point
        return result








