use super::{RawWarnings, UnicodeToEwtsMaps, UnicodeWarningKind};
use crate::dict::{Con, ConSpec, Final, Sign, Vowel};
use crate::util::{can_prefix, can_suffix2, is_root_first, is_standard_pair, is_standard_triple, is_suffix};
fn plus() -> &'static str {
ConSpec::Plus.get().0
}
#[derive(Default)]
struct Vowels {
first: Option<Vowel>,
rest: Vec<Vowel>,
}
impl Vowels {
fn is_empty(&self) -> bool {
self.first.is_none()
}
fn push(&mut self, v: Vowel) {
match self.first {
None => self.first = Some(v),
Some(_) => self.rest.push(v),
}
}
fn last_mut(&mut self) -> Option<&mut Vowel> {
self.rest.last_mut().or(self.first.as_mut())
}
fn iter(&self) -> impl Iterator<Item = Vowel> + '_ {
self.first.iter().chain(&self.rest).copied()
}
}
#[derive(Default)]
struct Stack {
cons: Vec<Con>,
vowels: Vowels,
finals: Vec<Final>,
tsa_phru: bool,
affix: bool,
dot: bool,
}
impl Stack {
fn single_cons(&self) -> Option<Con> {
match self.cons[..] {
[c] if !self.tsa_phru && self.vowels.is_empty() && self.finals.is_empty() => Some(c),
_ => None,
}
}
fn starts_with_a_chen(&self) -> bool {
self.cons.first().is_none_or(|&c| c == Con::AChen)
}
}
#[inline]
fn parse_stack(maps: &UnicodeToEwtsMaps, chars: &[char], mut i: usize, warnings: &mut RawWarnings) -> (Stack, usize) {
let mut st = Stack::default();
let mut max_rank = 0;
if let Some(Sign::Base(e)) = maps.sign(chars[i]) {
st.cons.push(e);
}
i += 1;
while let Some(&c) = chars.get(i) {
let mut repeated = false;
let rank = match maps.sign(c) {
Some(Sign::Sub(e)) => {
st.cons.push(e);
0
}
Some(Sign::Vowel(v)) => {
match (st.vowels.last_mut(), long_vowel(c)) {
(Some(prev @ Vowel::ABig), Some(long)) => *prev = long,
_ => st.vowels.push(v),
}
1
}
Some(Sign::Final(Final::TsaPhru)) => {
repeated = st.tsa_phru;
st.tsa_phru = true;
2
}
Some(Sign::Final(f)) => {
st.finals.push(f);
3
}
_ => break,
};
if rank < max_rank || repeated {
warnings.push((UnicodeWarningKind::SignOrder, i));
}
max_rank = max_rank.max(rank);
i += 1;
}
if st.cons == [Con::AChen] && !st.vowels.is_empty() {
st.cons.clear();
}
if st.tsa_phru {
let fv = match st.cons[..] {
[Con::Ph] => Some(Con::F),
[Con::B] => Some(Con::V),
_ => None,
};
if let Some(fv) = fv {
st.cons[0] = fv;
st.tsa_phru = false;
}
}
(st, i)
}
#[inline]
fn long_vowel(second: char) -> Option<Vowel> {
let a_long = Vowel::ABig.get().1;
Vowel::list().iter().copied().find(|v| {
v.get()
.1
.strip_prefix(a_long)
.is_some_and(|rest| rest.chars().eq([second]))
})
}
#[inline]
pub(super) fn push_tsekbar(
maps: &UnicodeToEwtsMaps,
chars: &[char],
mut i: usize,
out: &mut String,
warnings: &mut RawWarnings,
) -> usize {
let mut stacks = Vec::new();
loop {
let (st, next) = parse_stack(maps, chars, i, warnings);
i = next;
let visarga = st.finals.contains(&Final::Visarga);
stacks.push(st);
if visarga || !matches!(chars.get(i).and_then(|&c| maps.sign(c)), Some(Sign::Base(_))) {
break;
}
}
mark_affixes(&mut stacks);
for st in &stacks {
push_stack(st, out);
}
i
}
#[inline]
fn mark_affixes(stacks: &mut [Stack]) {
let n = stacks.len();
let last = n - 1;
let (mut prefix, mut suffix, mut suffix2_pair) = (false, false, false);
if n > 1 {
if let Some(p) = stacks[0].single_cons() {
prefix = can_prefix(p, &stacks[1].cons);
}
if let Some(s) = stacks[last].single_cons() {
suffix = is_suffix(s);
}
}
if n > 2
&& let (Some(s1), Some(s2)) = (stacks[last - 1].single_cons(), stacks[last].single_cons())
{
suffix2_pair = is_suffix(s1) && can_suffix2(s2, s1);
}
if n == 2 && prefix && suffix {
prefix = false;
}
if n == 3 && prefix && suffix2_pair {
let letters = [0, 1, 2].map(|k| stacks[k].cons[0]);
if is_root_first(&letters) {
prefix = false;
} else {
suffix2_pair = false;
}
}
if prefix {
let (prefix, root) = (&stacks[0].cons, &stacks[1].cons);
stacks[0].dot =
is_standard_joined(prefix, root) || (!is_plain_stack(root) && is_standard_joined(prefix, &root[..1]));
}
if suffix2_pair {
stacks[last - 1].dot = is_standard_joined(&stacks[last - 1].cons, &stacks[last].cons);
}
stacks[0].affix = prefix;
stacks[last].affix |= suffix || suffix2_pair;
if suffix2_pair {
stacks[last - 1].affix = true;
}
for k in 1..n {
let prev = &stacks[k - 1];
let prev_ends_with_a_chen =
prev.cons.last() == Some(&Con::AChen) && prev.vowels.is_empty() && prev.finals.is_empty() && !prev.tsa_phru;
let written_as_vowel = stacks[k].cons.len() <= 1 && !stacks[k].vowels.is_empty();
if stacks[k].starts_with_a_chen() && (written_as_vowel || prev_ends_with_a_chen) {
stacks[k - 1].dot = true;
}
}
}
#[inline]
fn push_stack(st: &Stack, out: &mut String) {
let sep = if is_plain_stack(&st.cons) { "" } else { plus() };
for (k, c) in st.cons.iter().enumerate() {
if k > 0 {
out.push_str(sep);
}
out.push_str(c.get().0);
}
if !st.vowels.is_empty() {
if st.cons.last() == Some(&Con::AChen) {
out.push_str(plus());
}
for (k, v) in st.vowels.iter().enumerate() {
if k > 0 {
out.push_str(plus());
}
out.push_str(v.get().0);
}
} else if !st.affix && st.cons.last() != Some(&Con::AChen) {
out.push_str(Con::AChen.get().0);
}
if st.tsa_phru {
out.push_str(Final::TsaPhru.get().0);
}
st.finals.iter().for_each(|f| out.push_str(f.get().0));
if st.dot {
out.push_str(ConSpec::Period.get().0);
}
}
fn is_plain_stack(cons: &[Con]) -> bool {
cons.len() <= 1 || is_standard_stack(cons)
}
fn is_standard_stack(cons: &[Con]) -> bool {
match *cons {
[top, bottom] => is_standard_pair(top, bottom),
[top, middle, bottom] => is_standard_triple(top, middle, bottom),
_ => false,
}
}
fn is_standard_joined(top: &[Con], bottom: &[Con]) -> bool {
let n = top.len() + bottom.len();
if n > 3 {
return false;
}
let mut joined = [Con::K; 3];
joined[..top.len()].copy_from_slice(top);
joined[top.len()..n].copy_from_slice(bottom);
is_standard_stack(&joined[..n])
}