/**
 * Copyright (c) 2021 Dominic Masters
 * 
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

#include "language.h"

void languageInit(language_t *language, char *filename) {
  // Open the asset buffer
  language->asset = assetBufferOpen(filename);

  // Get the headers
  csvHeadersGet(language->asset, &language->header);

  // Get the row indexes
  language->headerIndexKey = csvColumnGetIndex(
    &language->header, LANGUAGE_HEADER_KEY
  );
  language->headerIndexValue = csvColumnGetIndex(
    &language->header, LANGUAGE_HEADER_VALUE
  );
}

int32_t languageGet(
  language_t *language, char *key, char output[CSV_CELL_SIZE_MAX]
) {
  csvrow_t row;
  // Reset the buffer
  assetBufferStart(language->asset);

  // Search the CSV
  int32_t rowIndex = csvRowSearch(
    language->asset, &row, language->headerIndexKey, key
  );
  if(rowIndex == -1) return rowIndex;// Didn't find anything

  // Copy the string
  arrayCopy(
    sizeof(char), row.columns[language->headerIndexValue],
    CSV_CELL_SIZE_MAX, output
  );
  return rowIndex;
}

int32_t languageGetAndParse(language_t *language, char *key,
  stringhandlebarvariable_t *variables, int32_t variableCount, char *buffer
) {
  char csvBuffer[CSV_CELL_SIZE_MAX];
  int32_t i = languageGet(language, key, csvBuffer);
  if(i == -1) return -1;
  return stringHandlebarsBuffer(csvBuffer, variables, variableCount, buffer);
}

void languageDispose(language_t *language) {
  assetBufferClose(language->asset);
}