# -*- coding: utf-8 -*-
from __future__ import print_function

"""
Script: ImportGvlFromCsv.py
Version / Versão: 1.0.0.0
Created on / Data de criação: 2025-08-01
Description / Descrição:
    EN: Imports a CSV file and updates the textual declaration of a GVL in the project.
    PT: Importa um arquivo CSV e atualiza a declaração textual de uma GVL no projeto.

Changelog / Histórico de versões:
    - 1.0.0.0:
        EN: Initial version.
        PT: Versão inicial.
"""

import scriptengine
import os
import csv
import codecs

def ImportGvlFromCsv(GVL_name, FilePath):
    """
    Imports a CSV file containing GVL variable data and updates the GVL declaration.

    Importa um arquivo CSV contendo dados de variáveis GVL e atualiza a declaração da GVL.

    Parameters / Parâmetros:
    - GVL_name (str): Name of the GVL to update / Nome da GVL a ser atualizada
    - FilePath (str): Full path to the CSV file / Caminho completo do arquivo CSV
    """

    # Check if file exists / Verifica se o arquivo existe
    if not os.path.exists(FilePath):
        scriptengine.system.ui.error("[Erro] Arquivo não encontrado: {}".format(FilePath))
        print("[Error] File not found: {}".format(FilePath))
        print("[Erro] Arquivo não encontrado: {}".format(FilePath))
        return

    GVL_Dict = {}

    try:
        # Open and read CSV file / Abre e lê o arquivo CSV
        with codecs.open(FilePath, 'r', encoding='utf-8') as csvfile:
            reader = csv.DictReader(csvfile, delimiter=';')
            for row in reader:
                scope = row["Scope"].strip()
                name = row["Name"].strip()
                comment = row["Comment"].strip()

                # Add inline comment if present / Adiciona comentário inline se houver
                if comment:
                    var_line = '{} //{}'.format(name, comment)
                else:
                    var_line = name

                # Group variables by scope / Agrupa variáveis por escopo
                if scope not in GVL_Dict:
                    GVL_Dict[scope] = [var_line]
                else:
                    GVL_Dict[scope].append(var_line)
    except Exception as e:
        scriptengine.system.ui.error("[Erro] Falha ao ler o CSV: {}".format(str(e)))
        print("[Error] Failed to read CSV: {}".format(str(e)))
        print("[Erro] Falha ao ler o CSV: {}".format(str(e)))
        return

    # Build the textual declaration / Monta a declaração textual
    GVL_Text = ''
    for scope, var_lines in GVL_Dict.items():
        GVL_Text += scope + '\n'
        for var in var_lines:
            GVL_Text += '    ' + var + '\n'
        GVL_Text += 'END_VAR\n'

    try:
        # Update GVL in the project / Atualiza a GVL no projeto
        proj = scriptengine.projects.primary
        obj = proj.find(GVL_name, recursive=True)[0]
        obj.textual_declaration.replace(GVL_Text)
        print("[Success] GVL '{}' updated from CSV.".format(GVL_name))
        print("[Sucesso] GVL '{}' atualizada a partir do CSV.".format(GVL_name))
        scriptengine.system.ui.info("[Sucesso] GVL '{}' atualizada a partir do CSV.".format(GVL_name))
    except Exception as e:
        scriptengine.system.ui.error("[Erro] Falha ao atualizar a GVL: {}".format(str(e)))
        print("[Error] Failed to update GVL: {}".format(str(e)))
        print("[Erro] Falha ao atualizar a GVL: {}".format(str(e)))

resultado = PromptResult.No
gvl_name = ""
gvl_location = ""

try:
    while resultado != PromptResult.Yes and resultado != PromptResult.Cancel:    
        gvl_name = scriptengine.system.ui.query_string("Digite o nome da GVL a ser importada: ", "", "")
        gvl_location = scriptengine.system.ui.query_string("Digite o caminho para importar a GVL: ", "C:\\temp\GVL_Exported.csv", "")

        resultado = scriptengine.system.ui.prompt("Os valores abaixo estão corretos? \n\nNome da GVL: " + gvl_name + " \nCaminho: " + gvl_location, PromptChoice.YesNoCancel, PromptResult.Cancel) # Prompt - Options
        print(resultado)

    print("gvl_name = " + gvl_name)
    print("gvl_location = " + gvl_location)
except Exception as e:
        scriptengine.system.ui.error("Erro durante entrada de valores!")

if resultado == PromptResult.Yes:
    ImportGvlFromCsv(gvl_name, gvl_location)
