1import { getResourceXMLPathAsync } from './Paths';
2import {
3  buildResourceItem,
4  getObjectAsResourceItems,
5  getResourceItemsAsObject,
6  ResourceItemXML,
7  ResourceKind,
8  ResourceXML,
9} from './Resources';
10
11export function getProjectColorsXMLPathAsync(
12  projectRoot: string,
13  { kind }: { kind?: ResourceKind } = {}
14) {
15  return getResourceXMLPathAsync(projectRoot, { kind, name: 'colors' });
16}
17
18export function setColorItem(itemToAdd: ResourceItemXML, colorFileContentsJSON: ResourceXML) {
19  if (colorFileContentsJSON.resources?.color) {
20    const colorNameExists = colorFileContentsJSON.resources.color.filter(
21      (e: ResourceItemXML) => e.$.name === itemToAdd.$.name
22    )[0];
23    if (colorNameExists) {
24      colorNameExists._ = itemToAdd._;
25    } else {
26      colorFileContentsJSON.resources.color.push(itemToAdd);
27    }
28  } else {
29    if (!colorFileContentsJSON.resources || typeof colorFileContentsJSON.resources === 'string') {
30      //file was empty and JSON is `{resources : ''}`
31      colorFileContentsJSON.resources = {};
32    }
33    colorFileContentsJSON.resources.color = [itemToAdd];
34  }
35  return colorFileContentsJSON;
36}
37
38export function removeColorItem(named: string, contents: ResourceXML) {
39  if (contents.resources?.color) {
40    const index = contents.resources.color.findIndex((e: ResourceItemXML) => e.$.name === named);
41    if (index > -1) {
42      // replace the previous value
43      contents.resources.color.splice(index, 1);
44    }
45  }
46  return contents;
47}
48
49/**
50 * Set or remove value in XML based on nullish factor of the `value` property.
51 */
52export function assignColorValue(
53  xml: ResourceXML,
54  {
55    value,
56    name,
57  }: {
58    value?: string | null;
59    name: string;
60  }
61) {
62  if (value) {
63    return setColorItem(
64      buildResourceItem({
65        name,
66        value,
67      }),
68      xml
69    );
70  }
71
72  return removeColorItem(name, xml);
73}
74
75/**
76 * Helper to convert a basic XML object into a simple k/v pair.
77 * `colors.xml` is a very basic XML file so this is pretty safe to do.
78 * Added for testing purposes.
79 *
80 * @param xml
81 * @returns
82 */
83export function getColorsAsObject(xml: ResourceXML): Record<string, string> | null {
84  if (!xml?.resources?.color) {
85    return null;
86  }
87
88  return getResourceItemsAsObject(xml.resources.color);
89}
90
91/**
92 * Helper to convert a basic k/v object to a colors XML object.
93 *
94 * @param xml
95 * @returns
96 */
97export function getObjectAsColorsXml(obj: Record<string, string>): ResourceXML {
98  return {
99    resources: {
100      color: getObjectAsResourceItems(obj),
101    },
102  };
103}
104