summaryrefslogtreecommitdiff
path: root/src/program.py
blob: 1c43ea7ae6df9638825ac57d4def663e568470f4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from src.arg_parser import ArgParser
from src.table import Table
from src.exceptions import IncompatibleRowLengthError
import sys

class Program():
    def __init__(self, args=sys.argv[1:]):
        self.arg_parser = ArgParser(args=args)
        self.table = Table(self.arg_parser.file)

    def _command_arg_to_int(self):
        try:
            return int(self.arg_parser.command[1])
        except ValueError:
            self.arg_parser.print_help()
            exit()

    def _print_table_result(self, table):
        for row in table:
            print(row)

    def run(self):
        match self.arg_parser.command[0]:
            case 'row-at':
                print(self.table.row_at(self._command_arg_to_int()))
            case 'get-rows':
                result = self.table.get_rows(self._command_arg_to_int())

                self._print_table_result(result)
            case 'insert':
                new_row = tuple(self.arg_parser.command[1].rsplit(','))

                try:
                    self.table.insert(new_row)
                    print('Row added!')
                except IncompatibleRowLengthError as error:
                    print(error)
            case 'search':
                result = self.table.search(self.arg_parser.command[1])

                if result is not None:
                    print(result)
                else:
                    print('Not found!')
            case 'delete-at':
                try: 
                    self.table.delete_at(self._command_arg_to_int())
                    print(f"Row at {self._command_arg_to_int()} deleted")
                except IndexError:
                    print(f"Couldn't find row at {self._command_arg_to_int()}")
            case _:
                arg_parser.print_help()