import gspread
import json
import codecs


def add_underscore_at_position(text, position):
    # Split the string into a list of words
    words = text.split()

    # Check if the text contains less than two words
    if len(words) < 2:
        return text

    # Check if the position is valid
    if position < 0 or position >= len(words) - 1:
        raise ValueError("Invalid position for underscore")

    # Add the underscore between the words at the specified position
    words[position] = words[position] + '_' + words[position + 1]
    
    # Remove the word at the next position since it's already added
    del words[position + 1]
    
    # Join the list back into a string
    result = ' '.join(words)
    
    return result


# values by google sheets are returned like "Gold (Gl\u00e4nzend)"
def decode_unicode_escapes(text):
    # Decode Unicode escape sequences
    return codecs.decode(text, 'unicode_escape')


def update_grouptask_products_list_options(index_json_path, products_list):
  with open(index_json_path, 'r', encoding='utf-8') as json_file:
    data = json.load(json_file)

  options_list = []
  for product in products_list:
    # replace _ with " " just for better style in dashboard
    product_name = product['name'].replace("_", " ")

    option = f"#{product['id']} {product_name}, {product['product_variant']}, {product['product_color']}"
    options_list.append(option)

  for task in data['tasks']:
    for parameter in task['parameters']:
        if parameter['parameterName'] == 'product_type_id':
            parameter['options'] = options_list

  with open(index_json_path, 'w', encoding='utf-8') as output_file:
    json.dump(data, output_file, ensure_ascii=False, indent=2)


def google_sheets_products():
  gc = gspread.service_account(filename="../../secrets/shinnex-424321-b88b144bc9ef.json")
  
  spreadsheet = gc.open("Produkte")

  worksheet = spreadsheet.get_worksheet(0)

  data = worksheet.get_all_values()

  products = []

  for row in data[2:]:
    if row[0] == "":
      continue

    products.append({
      "id": row[0],
      "name": add_underscore_at_position(row[1], int(row[25])),
      "product_variant": row[2],
      "product_color": row[3]
    })

  products_dict = {"products": products}

  # Write the products list to a JSON file
  with open('../../groupsData/google-sheet-products.json', 'w', encoding='utf-8') as json_file:
    json.dump(products_dict, json_file, ensure_ascii=False, indent=2)

  update_grouptask_products_list_options("../../groups/shx-product-label/index.json", products)
  update_grouptask_products_list_options("../../groups/shx-all-in-one-order/index.json", products)

  print("Finished. Do not forget to reload the group configuration")


google_sheets_products()