// shared_strings_table - A module for storing Excel shared strings.
//
// Excel doesn't store strings directly in the worksheet?.xml files. Instead
// it stores them in a hash table with an index number, based on the order of
// writing and writes the index to the worksheet instead.
//
// SPDX-License-Identifier: MIT OR Apache-2.0
//
// Copyright 2022-2026, John McNamara, jmcnamara@cpan.org

mod tests;

use std::{collections::HashMap, sync::Arc};

//
// A metadata struct to store Excel unique strings between worksheets.
//
pub struct SharedStringsTable {
    pub count: u32,
    pub unique_count: u32,
    pub strings: HashMap<Arc<str>, u32>,
}

impl SharedStringsTable {
    // -----------------------------------------------------------------------
    // Crate public methods.
    // -----------------------------------------------------------------------

    // Create a new struct to track Excel shared strings between worksheets.
    pub(crate) fn new() -> SharedStringsTable {
        SharedStringsTable {
            count: 0,
            unique_count: 0,
            strings: HashMap::new(),
        }
    }

    // Get the index of the string in the Shared String table.
    pub(crate) fn shared_string_index(&mut self, key: Arc<str>) -> u32 {
        let index = *self.strings.entry(key).or_insert_with(|| {
            let index = self.unique_count;
            self.unique_count += 1;
            index
        });
        self.count += 1;
        index
    }

    // Add a string to the Shared String table to get a consistent ordering with
    // files generated by Excel, when testing. This doesn't increment the count.
    pub(crate) fn populate_string_index(&mut self, key: Arc<str>, index: u32) {
        self.strings.entry(key).or_insert_with(|| {
            self.unique_count += 1;
            index
        });
    }
}
