// this file is auto-generated by hap-codegen

use serde::ser::{Serialize, SerializeStruct, Serializer};

use crate::{
	accessory::{AccessoryInformation, HapAccessory},
	service::{HapService, accessory_information::AccessoryInformationService, wi_fi_router::WiFiRouterService},
	HapType,
	Result,
};

/// Wi-Fi Router accessory.
#[derive(Debug, Default)]
pub struct WiFiRouterAccessory {
    /// ID of the Wi-Fi Router Accessory.
    id: u64,

    /// Accessory Information service.
    pub accessory_information: AccessoryInformationService,
    /// Wi-Fi Router service.
    pub wi_fi_router: WiFiRouterService,
}

impl WiFiRouterAccessory {
    /// Creates a new Wi-Fi Router accessory.
    pub fn new(id: u64, information: AccessoryInformation) -> Result<Self> {
        let accessory_information = information.to_service(1, id)?;
        let wi_fi_router_id = accessory_information.get_characteristics().len() as u64;
        let mut wi_fi_router = WiFiRouterService::new(1 + wi_fi_router_id + 1, id);
        wi_fi_router.set_primary(true);

        Ok(Self {
            id,
            accessory_information,
            wi_fi_router,
        })
    }
}

impl HapAccessory for WiFiRouterAccessory {
    fn get_id(&self) -> u64 {
        self.id
    }

    fn set_id(&mut self, id: u64) {
        self.id = id;
    }

    fn get_service(&self, hap_type: HapType) -> Option<&dyn HapService> {
        for service in self.get_services() {
            if service.get_type() == hap_type {
                return Some(service);
            }
        }
        None
    }

    fn get_mut_service(&mut self, hap_type: HapType) -> Option<&mut dyn HapService> {
        for service in self.get_mut_services() {
            if service.get_type() == hap_type {
                return Some(service);
            }
        }
        None
    }

    fn get_services(&self) -> Vec<&dyn HapService> {
        vec![
            &self.accessory_information,
            &self.wi_fi_router,
        ]
    }

    fn get_mut_services(&mut self) -> Vec<&mut dyn HapService> {
        vec![
            &mut self.accessory_information,
            &mut self.wi_fi_router,
        ]
    }
}

impl Serialize for WiFiRouterAccessory {
    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        let mut state = serializer.serialize_struct("HapAccessory", 2)?;
        state.serialize_field("aid", &self.get_id())?;
        state.serialize_field("services", &self.get_services())?;
        state.end()
    }
}
