import csv
import os
from clients.models import Client

class ClientsServices():
    def __init__(self, database) -> None:
        self.database = database
        self.database_tmp = f'{database}.tmp'

    def create_client(self, client):
        with open(self.database, mode='a') as f:
            writer  = csv.DictWriter(f, fieldnames=Client.schema())
            writer.writerow(client.to_dict())

    def read_clients(self):
        with open(self.database, mode='r') as f:
            reader = csv.DictReader(f, fieldnames=Client.schema())

            return list(reader)

    def update_client(self, update_client):
        all_clients = self.read_clients()
        update_clients = []
        for client in all_clients:
            if client["uid"] == update_client.uid:
                update_clients.append(update_client.to_dict())
            else: 
                update_clients.append(client)
        self._save_database(update_clients)

    def _save_database(self, clients):
        with open(self.database_tmp, mode='w') as f:
            writer = csv.DictWriter(f, fieldnames=Client.schema())
            writer.writerows(clients)
            os.remove(self.database)
            os.rename(self.database_tmp, self.database)

    def delete_client(self, delete_uid):
        all_rows = self.read_clients()
        update_data = [row for row in all_rows if row["uid"] != delete_uid]
        self._save_database(update_data)

import csv
import os
from clients.models import Client

class ClientsServices():
    def __init__(self, database) -> None:
        self.database = database
        self.database_tmp = f'{database}.tmp'

    def create_client(self, client):
        with open(self.database, mode='a') as f:
            writer  = csv.DictWriter(f, fieldnames=Client.schema())
            writer.writerow(client.to_dict())

    def read_clients(self):
        with open(self.database, mode='r') as f:
            reader = csv.DictReader(f, fieldnames=Client.schema())

            return list(reader)

    def update_client(self, update_client):
        all_clients = self.read_clients()
        update_clients = []
        for client in all_clients:
            if client["uid"] == update_client.uid:
                update_clients.append(update_client.to_dict())
            else: 
                update_clients.append(client)
        self._save_database(update_clients)

    def _save_database(self, clients):
        with open(self.database_tmp, mode='w') as f:
            writer = csv.DictWriter(f, fieldnames=Client.schema())
            writer.writerows(clients)
            os.remove(self.database)
            os.rename(self.database_tmp, self.database)

    def delete_client(self, delete_uid):
        all_rows = self.read_clients()
        update_data = [row for row in all_rows if row["uid"] != delete_uid]
        self._save_database(update_data)
