/*
    Copyright: 2020 Rasmus Thomsen <oss@cogitri.dev>
    SPDX-License-Identifier: GPL-3.0-or-later
*/

use apk_tools::PackageState;
use serde::Serialize;
use std::cmp::Ordering;
use std::convert::TryFrom;

/**
* An owned variant of ApkPackage, in cases where the lifetime restrictions of ApkPackage are too tight.
*/
#[derive(Serialize, Debug, Eq, zvariant_derive::Type)]
pub struct ApkPackageOwned {
    pub name: String,
    pub new_version: String,
    pub description: String,
    pub license: String,
    pub old_version: String,
    pub url: String,
    pub installed_size: u64,
    pub size: u64,
    pub package_state: PackageState,
}

impl PartialOrd for ApkPackageOwned {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.name.cmp(&other.name))
    }
}

impl Ord for ApkPackageOwned {
    fn cmp(&self, other: &Self) -> Ordering {
        self.name.cmp(&other.name)
    }
}

// size and installed_size can differ slightly between the same package when built
// at different machines/on different days if they're not reprocible.
impl PartialEq for ApkPackageOwned {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && self.new_version == other.new_version
            && self.description == other.description
            && self.license == other.license
            && self.url == other.url
            && self.package_state == other.package_state
    }
}

impl<'a> From<apk_tools::ApkPackage<'a>> for ApkPackageOwned {
    fn from(pkg: apk_tools::ApkPackage) -> Self {
        ApkPackageOwned {
            name: pkg.name().to_string(),
            new_version: pkg.new_version(),
            description: pkg.description().unwrap_or("").to_string(),
            license: pkg.license().unwrap_or_else(|| "".to_string()),
            old_version: pkg.old_version().unwrap_or("").to_string(),
            url: pkg.url().unwrap_or("").to_string(),
            installed_size: u64::try_from(pkg.installed_size()).unwrap_or(0),
            size: u64::try_from(pkg.size()).unwrap_or(0),
            package_state: pkg.package_state(),
        }
    }
}
