aboutsummaryrefslogtreecommitdiff
path: root/Assets/Scripts/Localisation/CSVLoader.cs
blob: 6805761c2765eaa46db93adcd6d46723ca91754d (plain) (blame)
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;

public class CSVLoader
{
   //Reference file;
   private TextAsset csvFile;
   private char lineSeperator = '\n';
   private char surrond = '"';
   private string[] fieldSeperator = { "\", \"" };

   public void LoadCSV()
   {
       csvFile = Resources.Load<TextAsset>("localisation");
   }

   public Dictionary<string, string> GetDictionaryValues(string attributeID)
   {
       Dictionary<string, string> dictionary = new Dictionary<string, string>();
       
       string[] lines = csvFile.text.Split(lineSeperator);

       int attributeIndex = -1;
       
       string[] headers = lines[0].Split(fieldSeperator, StringSplitOptions.None);

       for(int i=0; i<headers.Length; i++)
       {
           if(headers[i].Contains(attributeID))
           {
               attributeIndex = i;
               break;
           }
       }

       Regex CSVParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");

       for(int i=1; i<lines.Length; i++)
       {
           string line = lines[i];

           string[] fields = CSVParser.Split(line);

           for(int f=0; f<fields.Length; f++)
           {
               fields[f] = fields[f].TrimStart(' ', surrond);
               fields[f] = fields[f].TrimEnd(surrond);
           }

           if(fields.Length > attributeIndex)
           {
               var key = fields[0];
               
               if (dictionary.ContainsKey(key)) { continue; }

               var value = fields[attributeIndex];

               dictionary.Add(key, value);
           }
       }

       return dictionary;
   }

}