/*
 * This file is part of CycloneDX Rust Cargo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 */

use crate::{
    errors::XmlReadError,
    external_models::{normalized_string::NormalizedString, uri::Uri},
    models,
    xml::{
        read_lax_validation_tag, read_simple_tag, to_xml_read_error, to_xml_write_error,
        unexpected_element_error, write_simple_tag, FromXml, ToXml,
    },
};
use serde::{Deserialize, Serialize};
use xml::{reader, writer::XmlEvent};

#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub(crate) struct VulnerabilitySource {
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    url: Option<String>,
}

impl From<models::vulnerability_source::VulnerabilitySource> for VulnerabilitySource {
    fn from(other: models::vulnerability_source::VulnerabilitySource) -> Self {
        Self {
            name: other.name.map(|n| n.to_string()),
            url: other.url.map(|u| u.to_string()),
        }
    }
}

impl From<VulnerabilitySource> for models::vulnerability_source::VulnerabilitySource {
    fn from(other: VulnerabilitySource) -> Self {
        Self {
            name: other.name.map(NormalizedString::new_unchecked),
            url: other.url.map(Uri),
        }
    }
}

const VULNERABILITY_SOURCE_TAG: &str = "source";
const NAME_TAG: &str = "name";
const URL_TAG: &str = "url";

impl ToXml for VulnerabilitySource {
    fn write_xml_element<W: std::io::Write>(
        &self,
        writer: &mut xml::EventWriter<W>,
    ) -> Result<(), crate::errors::XmlWriteError> {
        let vulnerability_source_start_tag = XmlEvent::start_element(VULNERABILITY_SOURCE_TAG);

        writer
            .write(vulnerability_source_start_tag)
            .map_err(to_xml_write_error(VULNERABILITY_SOURCE_TAG))?;

        if let Some(name) = &self.name {
            write_simple_tag(writer, NAME_TAG, name)?;
        }

        if let Some(url) = &self.url {
            write_simple_tag(writer, URL_TAG, url)?;
        }

        writer
            .write(XmlEvent::end_element())
            .map_err(to_xml_write_error(VULNERABILITY_SOURCE_TAG))?;

        Ok(())
    }
}

impl FromXml for VulnerabilitySource {
    fn read_xml_element<R: std::io::Read>(
        event_reader: &mut xml::EventReader<R>,
        element_name: &xml::name::OwnedName,
        _attributes: &[xml::attribute::OwnedAttribute],
    ) -> Result<Self, XmlReadError>
    where
        Self: Sized,
    {
        let mut source_name: Option<String> = None;
        let mut url: Option<String> = None;

        let mut got_end_tag = false;
        while !got_end_tag {
            let next_element = event_reader
                .next()
                .map_err(to_xml_read_error(VULNERABILITY_SOURCE_TAG))?;
            match next_element {
                reader::XmlEvent::StartElement { name, .. } if name.local_name == NAME_TAG => {
                    source_name = Some(read_simple_tag(event_reader, &name)?);
                }

                reader::XmlEvent::StartElement { name, .. } if name.local_name == URL_TAG => {
                    url = Some(read_simple_tag(event_reader, &name)?)
                }

                // lax validation of any elements from a different schema
                reader::XmlEvent::StartElement { name, .. } => {
                    read_lax_validation_tag(event_reader, &name)?
                }
                reader::XmlEvent::EndElement { name } if &name == element_name => {
                    got_end_tag = true;
                }
                unexpected => return Err(unexpected_element_error(element_name, unexpected)),
            }
        }

        Ok(Self {
            name: source_name,
            url,
        })
    }
}

#[cfg(test)]
pub(crate) mod test {
    use super::*;
    use pretty_assertions::assert_eq;

    use crate::xml::test::{read_element_from_string, write_element_to_string};

    pub(crate) fn example_vulnerability_source() -> VulnerabilitySource {
        VulnerabilitySource {
            name: Some("name".to_string()),
            url: Some("url".to_string()),
        }
    }

    pub(crate) fn corresponding_vulnerability_source(
    ) -> models::vulnerability_source::VulnerabilitySource {
        models::vulnerability_source::VulnerabilitySource {
            name: Some(NormalizedString::new_unchecked("name".to_string())),
            url: Some(Uri("url".to_string())),
        }
    }

    #[test]
    fn it_should_write_xml_full() {
        let xml_output = write_element_to_string(example_vulnerability_source());
        insta::assert_snapshot!(xml_output);
    }

    #[test]
    fn it_should_read_xml_full() {
        let input = r#"
<source>
  <name>name</name>
  <url>url</url>
</source>
"#;
        let actual: VulnerabilitySource = read_element_from_string(input);
        let expected = example_vulnerability_source();
        assert_eq!(actual, expected);
    }
}
