1import { getResourceXMLPathAsync } from './Paths';
2import { ResourceItemXML, ResourceKind, ResourceXML } from './Resources';
3
4export async function getProjectStringsXMLPathAsync(
5  projectRoot: string,
6  { kind }: { kind?: ResourceKind } = {}
7): Promise<string> {
8  return getResourceXMLPathAsync(projectRoot, { kind, name: 'strings' });
9}
10
11export function setStringItem(
12  itemToAdd: ResourceItemXML[],
13  stringFileContentsJSON: ResourceXML
14): ResourceXML {
15  if (!stringFileContentsJSON?.resources?.string) {
16    if (!stringFileContentsJSON.resources || typeof stringFileContentsJSON.resources === 'string') {
17      // file was empty and JSON is `{resources : ''}`
18      stringFileContentsJSON.resources = {};
19    }
20    stringFileContentsJSON.resources.string = itemToAdd;
21    return stringFileContentsJSON;
22  }
23
24  for (const newItem of itemToAdd) {
25    const stringNameExists = stringFileContentsJSON.resources.string.findIndex(
26      (e: ResourceItemXML) => e.$.name === newItem.$.name
27    );
28    if (stringNameExists > -1) {
29      // replace the previous item
30      stringFileContentsJSON.resources.string[stringNameExists] = newItem;
31    } else {
32      stringFileContentsJSON.resources.string =
33        stringFileContentsJSON.resources.string.concat(newItem);
34    }
35  }
36  return stringFileContentsJSON;
37}
38
39export function removeStringItem(named: string, stringFileContentsJSON: ResourceXML): ResourceXML {
40  if (stringFileContentsJSON?.resources?.string) {
41    const stringNameExists = stringFileContentsJSON.resources.string.findIndex(
42      (e: ResourceItemXML) => e.$.name === named
43    );
44    if (stringNameExists > -1) {
45      // replace the previous value
46      stringFileContentsJSON.resources.string.splice(stringNameExists, 1);
47    }
48  }
49  return stringFileContentsJSON;
50}
51