import csv
import datetime
import json

# TODO: add another filetypes
from logging import getLogger

# Logger added
logger = getLogger(__name__)


def data_to_file(data: dict, filename: str = None):
    """Data To File


    :type data: dict
    :type filename: str
    :param data: given data to fill the file
    :param filename: name to create file and fill given data
    :raise Any: prints  error and returns 0
    :return: 1
    """

    # If no filename given
    if filename is None:
        filename = f'data_{datetime.datetime.now()}.csv'

    # Check if filename type is csv
    filename_in_list: list = filename.split('.')
    filename_type: str = filename_in_list[len(filename_in_list) - 1]

    try:

        # Open filename and edit
        with open(filename, 'w') as f:

            # If file type is csv
            logger.info(f'Opened {filename}')
            if filename_type == 'csv':
                logger.info(f'{filename} is csv')

                # Create Dictionary Writer
                writer = csv.DictWriter(f, fieldnames=[x for x in data.keys()])
                logger.info(f'DictWriter created successfully!')

                # Write Headers
                writer.writeheader()
                logger.info('Header written successfully!')

                # Write all rows
                writer.writerows(data)
                logger.info('Data rows written successfully! Returning 1')
                return 1
            logger.info(f'{filename} not csv')

            # If not csv
            f.write(json.dumps(data))
            logger.info('Data jsonified and written successfully!')
            return 1

    # if some error occurred
    except Exception as e:
        logger.error(f'Error while inserting data into {filename}')
        logger.error(f'Error message {e}')
        return 0

import csv
import datetime
import json

# TODO: add another filetypes
from logging import getLogger

# Logger added
logger = getLogger(__name__)


def data_to_file(data: dict, filename: str = None):
    """Data To File


    :type data: dict
    :type filename: str
    :param data: given data to fill the file
    :param filename: name to create file and fill given data
    :raise Any: prints  error and returns 0
    :return: 1
    """

    # If no filename given
    if filename is None:
        filename = f'data_{datetime.datetime.now()}.csv'

    # Check if filename type is csv
    filename_in_list: list = filename.split('.')
    filename_type: str = filename_in_list[len(filename_in_list) - 1]

    try:

        # Open filename and edit
        with open(filename, 'w') as f:

            # If file type is csv
            logger.info(f'Opened {filename}')
            if filename_type == 'csv':
                logger.info(f'{filename} is csv')

                # Create Dictionary Writer
                writer = csv.DictWriter(f, fieldnames=[x for x in data.keys()])
                logger.info(f'DictWriter created successfully!')

                # Write Headers
                writer.writeheader()
                logger.info('Header written successfully!')

                # Write all rows
                writer.writerows(data)
                logger.info('Data rows written successfully! Returning 1')
                return 1
            logger.info(f'{filename} not csv')

            # If not csv
            f.write(json.dumps(data))
            logger.info('Data jsonified and written successfully!')
            return 1

    # if some error occurred
    except Exception as e:
        logger.error(f'Error while inserting data into {filename}')
        logger.error(f'Error message {e}')
        return 0

# TODO: add another filetypes # Logger added Data To File       :type data: dict     :type filename: str     :param data: given data to fill the file     :param filename: name to create file and fill given data     :raise Any: prints  error and returns 0     :return: 1 # If no filename given # Check if filename type is csv # Open filename and edit # If file type is csv # Create Dictionary Writer # Write Headers # Write all rows # If not csv # if some error occurred