""" Script that tries to parse a dataset to profile its variables"""
import os
import sys

from databasehelper import DatabaseHelper
from profiler import Profiler


def main():
    """
    Main function of the program
    Arguments should be:
    1) path of the file to analyse
    2) format of the file
    3) id of the resource
    """

    if len(sys.argv) < 4:
        # TO!DO: Print to log
        print('Call should be: py <script.py> <path> <file_format> '
              '<resource_id>')
        return -1

    path = sys.argv[1]
    file_format = sys.argv[2]
    resource_id = sys.argv[3]

    if os.path.exists(path) and os.path.isfile(path):
        with open(path, 'rb') as file:
            profiler = Profiler(file, file_format.lower())
            profiler.profile_dataset()
            save_to_database(resource_id, profiler)

    return 0


def save_to_database(resource_id: int, profiler: Profiler):
    """ Save the structure of the dataset resource in the database """
    db_hlpr = DatabaseHelper()
    db_hlpr.open_connection()

    types = db_hlpr.get_variable_types_id(profiler.final_types)

    pfl_id = db_hlpr.create_profile(resource_id)
    tbl_id = db_hlpr.add_resource_table(pfl_id, offset_y=profiler.offset)

    length = len(profiler.final_types)
    variables = [None]*length

    for i in range(0, length):
        typ = profiler.final_types[i]
        if profiler.real_headers:
            name = profiler.real_headers[i]
        else:
            name = "Col-" + str(i)

        idt = db_hlpr.add_variable(tbl_id, i, types[typ], name)
        variables[i] = idt

    i = 0
    for row in profiler.row_set:
        if i < (profiler.offset+1):
            i = i + 1
            continue
        db_hlpr.add_row(tbl_id, i, row, variables)
        i = i + 1

    db_hlpr.close_connection()

if __name__ == "__main__":
    sys.exit(main())
