//! 解密密钥

use crate::{rand::RandList, vec_ref, DecodeError, DecodeTrait, EncodeResult, URLCode};

pub fn decode(e: &EncodeResult) -> Result<String, DecodeError> {
    let s = decode_urlcode(e);
    URLCode::decode(s)
}

pub fn decode_urlcode(e: &EncodeResult) -> String {
    let mut res = String::new();
    let decrypt = RandList::from(&e.key);
    vec_ref(&e.val).into_iter().enumerate().for_each(|(i, s)| {
        let index = decrypt.get_index(&s).expect("Can not find index at Decode");
        let mut index: isize = index as isize - i as isize;

        while index <= -1 || index >= decrypt.len() as isize + 1 {
            if index <= i as isize - 1 {
                index = index + decrypt.len() as isize;
            }

            if index >= decrypt.len() as isize + 1 {
                index = index - decrypt.len() as isize;
            }
        }

        res.push_str(decrypt.get(index as usize).unwrap());
    });

    res
}
