
    Vh]                         d dl mZmZmZ eZdZdZdZdZ	d dl
mZ d dlmZmZmZ dd	d
dddZ G d de      Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functionz?Madhan Sankaranarayanan, Rishita Chowdhary, Abhishek Maheshwaria  
---
module: site_intent
short_description: Resource module for Site operations
description:
  - Manage operation create, update and delete of the resource Sites.
  - Creates site with area/building/floor with specified hierarchy.
  - Updates site with area/building/floor with specified hierarchy.
  - Deletes site with area/building/floor with specified hierarchy.
version_added: '6.6.0'
extends_documentation_fragment:
  - cisco.dnac.intent_params
author: Madhan Sankaranarayanan (@madhansansel) Rishita Chowdhary (@rishitachowdhary)
  Abhishek Maheshwari (@abhishekmaheshwari)
options:
  config_verify:
    description: Set to True to verify the Cisco Catalyst Center config after applying
      the playbook config.
    type: bool
    default: false
  state:
    description: The state of Catalyst Center after module completion.
    type: str
    choices: [merged, deleted]
    default: merged
  config:
    description: It represents a list of details for creating/managing/deleting sites,
      including areas, buildings, and floors.
    type: list
    elements: dict
    required: true
    suboptions:
      site_type:
        description: Type of site to create/update/delete (eg area, building, floor).
        type: str
      site:
        description: Contains details about the site being managed including areas,
          buildings and floors.
        type: dict
        suboptions:
          area:
            description: Configuration details for creating or managing an area within
              a site.
            type: dict
            suboptions:
              name:
                description: Name of the area to be created or managed (e.g., "Area1").
                type: str
              parent_name:
                description: The full name of the parent under which the area will
                  be created/managed/deleted (e.g., "Global/USA").
                type: str
          building:
            description: Configuration details required for creating or managing a
              building within a site.
            type: dict
            suboptions:
              address:
                description: Physical address of the building that is to be created
                  or managed.
                type: str
              latitude:
                description: Geographical latitude coordinate of the building. For
                  example, use 37.338 for a location in San Jose, California. Valid
                  values range from -90.0 to +90.0 degrees.
                type: float
              longitude:
                description: Geographical longitude coordinate of the building. For
                  example, use -121.832 for a location in San Jose, California. Valid
                  values range from -180.0 to +180.0 degrees.
                type: float
              name:
                description: Name of the building (e.g., "Building1").
                type: str
              parent_name:
                description: Hierarchical parent path of the building, indicating
                  its location within the site (e.g., "Global/USA/San Francisco").
                type: str
          floor:
            description: Configuration details required for creating or managing a
              floor within a site.
            type: dict
            suboptions:
              height:
                description: Height of the floor in feet (e.g., 15.23).
                type: float
              length:
                description: Length of the floor in feet (e.g., 100.11).
                type: float
              name:
                description: Name of the floor (e.g., "Floor-1").
                type: str
              parent_name:
                description: Hierarchical parent path of the floor, indicating its
                  location within the site (e.g., "Global/USA/San Francisco/BGL_18").
                type: str
              rf_model:
                description: The RF (Radio Frequency) model type for the floor, which
                  is essential for simulating and optimizing wireless network coverage.
                  Select from the following allowed values, which describe different
                  environmental signal propagation characteristics. Type of floor
                  (allowed values are 'Cubes And Walled Offices', 'Drywall Office
                  Only', 'Indoor High Ceiling', 'Outdoor Open Space'). Cubes And Walled
                  Offices - This RF model typically represents indoor areas with cubicles
                  or walled offices, where radio signals may experience attenuation
                  due to walls and obstacles. Drywall Office Only - This RF model
                  indicates an environment with drywall partitions, commonly found
                  in office spaces, which may have moderate signal attenuation. Indoor
                  High Ceiling - This RF model is suitable for indoor spaces with
                  high ceilings, such as auditoriums or atriums, where signal propagation
                  may differ due to the height of the ceiling. Outdoor Open Space
                  - This RF model is used for outdoor areas with open spaces, where
                  signal propagation is less obstructed and may follow different patterns
                  compared to indoor environments.
                type: str
              width:
                description: Width of the floor in feet (e.g., 100.22).
                type: float
              floor_number:
                description: Floor number within the building site (e.g., 5). This
                  value can only be specified during the creation of the floor and
                  cannot be modified afterward.
                type: int
requirements:
  - dnacentersdk == 2.4.5
  - python >= 3.9
notes:
  - SDK Method used are sites.Sites.create_site, sites.Sites.update_site, sites.Sites.delete_site
  - Paths used are post /dna/intent/api/v1/site, put dna/intent/api/v1/site/{siteId},
    delete dna/intent/api/v1/site/{siteId}
a  
- name: Create a new area site
  cisco.dnac.site_intent:
    dnac_host: "{{dnac_host}}"
    dnac_username: "{{dnac_username}}"
    dnac_password: "{{dnac_password}}"
    dnac_verify: "{{dnac_verify}}"
    dnac_port: "{{dnac_port}}"
    dnac_version: "{{dnac_version}}"
    dnac_debug: "{{dnac_debug}}"
    dnac_log_level: "{{dnac_log_level}}"
    dnac_log: "{{dnac_log}}"
    state: merged
    config:
      - site:
          area:
            name: Test
            parent_name: Global/India
        site_type: area
- name: Create a new building site
  cisco.dnac.site_intent:
    dnac_host: "{{dnac_host}}"
    dnac_username: "{{dnac_username}}"
    dnac_password: "{{dnac_password}}"
    dnac_verify: "{{dnac_verify}}"
    dnac_port: "{{dnac_port}}"
    dnac_version: "{{dnac_version}}"
    dnac_debug: "{{dnac_debug}}"
    dnac_log_level: "{{dnac_log_level}}"
    dnac_log: "{{dnac_log}}"
    state: merged
    config:
      - site:
          building:
            name: Building_1
            parent_name: Global/India
            address: Bengaluru, Karnataka, India
            latitude: 24.12
            longitude: 23.45
        site_type: building
- name: Create a Floor site under the building
  cisco.dnac.site_intent:
    dnac_host: "{{dnac_host}}"
    dnac_username: "{{dnac_username}}"
    dnac_password: "{{dnac_password}}"
    dnac_verify: "{{dnac_verify}}"
    dnac_port: "{{dnac_port}}"
    dnac_version: "{{dnac_version}}"
    dnac_debug: "{{dnac_debug}}"
    dnac_log_level: "{{dnac_log_level}}"
    dnac_log: "{{dnac_log}}"
    state: merged
    config:
      - site:
          floor:
            name: Floor_1
            parent_name: Global/India/Building_1
            length: 75.76
            width: 35.54
            height: 30.12
            rf_model: Cubes And Walled Offices
            floor_number: 2
        site_type: floor
- name: Updating the Floor details under the building
  cisco.dnac.site_intent:
    dnac_host: "{{dnac_host}}"
    dnac_username: "{{dnac_username}}"
    dnac_password: "{{dnac_password}}"
    dnac_verify: "{{dnac_verify}}"
    dnac_port: "{{dnac_port}}"
    dnac_version: "{{dnac_version}}"
    dnac_debug: "{{dnac_debug}}"
    dnac_log_level: "{{dnac_log_level}}"
    dnac_log: "{{dnac_log}}"
    state: merged
    config:
      - site:
          floor:
            name: Floor_1
            parent_name: Global/India/Building_1
            length: 75.76
            width: 35.54
            height: 30.12
        site_type: floor
- name: Deleting any site you need site name and parent name
  cisco.dnac.site_intent:
    dnac_host: "{{dnac_host}}"
    dnac_username: "{{dnac_username}}"
    dnac_password: "{{dnac_password}}"
    dnac_verify: "{{dnac_verify}}"
    dnac_port: "{{dnac_port}}"
    dnac_version: "{{dnac_version}}"
    dnac_debug: "{{dnac_debug}}"
    dnac_log_level: "{{dnac_log_level}}"
    dnac_log: "{{dnac_log}}"
    state: deleted
    config:
      - site:
          floor:
            name: Floor_1
            parent_name: Global/India/Building_1
        site_type: floor
a^  
#Case_1: Site is successfully created/updated/deleted
response_1:
  description: A dictionary with API execution details as returned by the Cisco Catalyst Center Python SDK
  returned: always
  type: dict
  sample: >
    {
      "response":
        {
             "bapiExecutionId": String,
             "bapiKey": String,
             "bapiName": String,
             "endTime": String,
             "endTimeEpoch": 0,
             "runtimeInstanceId": String,
             "siteId": String,
             "startTime": String,
             "startTimeEpoch": 0,
             "status": String,
             "timeDuration": 0
        },
      "msg": "string"
    }
#Case_2: Site exits and does not need an update
response_2:
  description: A dictionary with existing site details.
  returned: always
  type: dict
  sample: >
    {
      "response":
      {
            "site": {},
            "siteId": String,
            "type": String
      },
      "msg": String
    }
#Case_3: Error while creating/updating/deleting site
response_3:
  description: A dictionary with API execution details as returned by the Cisco Catalyst Center Python SDK
  returned: always
  type: dict
  sample: >
    {
      "response":
        {
             "bapiError": String,
             "bapiExecutionId": String,
             "bapiKey": String,
             "bapiName": String,
             "endTime": String,
             "endTimeEpoch": 0,
             "runtimeInstanceId": String,
             "startTime": String,
             "startTimeEpoch": 0,
             "status": String,
             "timeDuration": 0
        },
      "msg": "string"
    }
#Case_4: Site not found when atempting to delete site
response_4:
  description: A list with the response returned by the Cisco Catalyst Center Python
  returned: always
  type: list
  sample: >
    {
       "response": [],
       "msg": String
    }
)AnsibleModule)DnacBasevalidate_list_of_dictsget_dict_resultzCubes And Walled OfficeszDrywall Office Onlyz
Free SpacezIndoor High CeilingzOutdoor Open Space)101101101102101105101104101103c                        e Zd ZdZ fdZd Zd Zd Zd Zd Z	ddZ
d	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z xZS )DnacSitez9Class containing member attributes for site intent modulec                     t         |   |       ddg| _        g g g c| _        | _        | _        g g c| _        | _        y )Nmergeddeleted)super__init__supported_statescreated_site_listupdated_site_listupdate_not_neeeded_sitesdeleted_site_listsite_absent_list)selfmodule	__class__s     j/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/cisco/dnac/plugins/modules/site_intent.pyr   zDnacSite.__init__O  sJ     !)9 5XZ\^`bU 68U8:B5 5    c                    | j                   s,d| _        d| _        | j                  | j                  d       | S t	        t	        dd      t	        dd      	      }| j                  | j                         | _         | j                  | j                         | _         t        | j                   |      \  }}|rJd
j                  dj                  |            | _        | j                  | j                  d       d| _        | S || _
        dj                  t        |            | _        | j                  | j                  d       d| _        | S )a@  
        Validate the fields provided in the playbook.
        Checks the configuration provided in the playbook against a predefined specification
        to ensure it adheres to the expected structure and data types.
        Parameters:
            self (object): An instance of a class used for interacting with Cisco Catalyst Center.
        Returns:
            The method returns an instance of the class with updated attributes:
                - self.msg: A message describing the validation result.
                - self.status: The status of the validation (either 'success' or 'failed').
                - self.validated_config: If successful, a validated version of the 'config' parameter.
        Example:
            To use this method, create an instance of the class and call 'validate_input' on it.
            If the validation succeeds, 'self.status' will be 'success' and 'self.validated_config'
            will contain the validated configuration. If it fails, 'self.status' will be 'failed', and
            'self.msg' will describe the validation issues.
        successz=Configuration is not available in the playbook for validationERRORFstrrequiredtypeTdictr'   sitez#Invalid parameters in playbook: {0}
failedz2Successfully validated playbook config params: {0}INFO)configstatusmsglogr(   camel_to_snake_caseupdate_site_type_keyr   formatjoinvalidated_configr$   )r   	temp_spec
valid_tempinvalid_paramss       r   validate_inputzDnacSite.validate_inputU  s   & {{#DKVDHHHTXXw'Ku51t&1
	 ..t{{;//< &<KK&
"
N <CC		.)DH HHTXXw'"DKK *GNNsS]_6"r    c                 d   i }t        |d   j                  d      dd      }|j                  d      j                  d      }|dk(  rdt        t        |d   j                  d      |d   j                  d	      j                  d
|d   j                  d      z         d               }n;|dk(  rt        t        |d   j                  d      |d   j                  d	      j                  d
|d   j                  d      z         d   |j                  d      j                  d      |j                  d      j                  d      |j                  d      j                  d      |j                  d      j                  d                  }nV|dk(  rPt        |d   j                  d      dd      }t        |d   j                  d      dd      }|j                  d      j                  d      }t        t        |d   j                  d      |d   j                  d	      j                  d
|d   j                  d      z         d   t        j                  |      |j                  d      j                  d      |j                  d      j                  d      |j                  d      j                  d      |j                  d      j                  d                  }t        |||d   j                  d            }| j                  d j                  t        |            d!       |S )"a  
        Get the current site information.
        Parameters:
          self (object): An instance of a class used for interacting with Cisco Catalyst Center.
          - site (list): A list containing information about the site.
        Returns:
          - dict: A dictionary containing the extracted site information.
        Description:
            This method extracts information about the current site based on
          the provided 'site' list. It determines the type of the site
          (area, building, or floor) and retrieves specific details
          accordingly. The resulting dictionary includes the type, site
          details, and the site ID.
        r   additionalInfo	nameSpaceLocation
attributesr'   areanamesiteNameHierarchy/rA   
parentName)r@   buildingaddresslatitude	longitudecountry)rA   rE   rG   rH   rI   rJ   )rF   floormapGeometrymapsSummaryrfModelwidthlengthheight
floorIndex)rA   rE   rf_modelrO   rP   rQ   floorNumber)rK   id)r'   r*   siteIdzCurrent site details: {0}r-   )r	   getr(   split
floor_planr1   r4   r$   )	r   r*   	site_infolocationtypeinfomap_geometrymap_summaryrS   current_sites	            r   get_current_sitezDnacSite.get_current_site  s     	"47;;/?#@+zZ<<-11&9vaV,#Aw{{+>?EEcDQRGKKX^L_F_`abcI #aV,#Aw{{+>?EEcDQRGKKX^L_F_`abc$LL6::9E%\\,7;;JG&ll<8<<[I$LL6::9E	I  *47;;7G+H+WdeL)$q'++6F*GVcdK"|488CHaV,#Aw{{+>?EEcDQRGKKX^L_F_`abc'^^H5&**<8<<WE'++L9==hG'++L9==hG + = A A, O
I 7;;t$
 	,33C4EFOr    c           	      @   d}i }d}	 | j                   j                  dddd| j                  j                  d      i      }|r|j                  d      }| j                  dj                  t        |            d       | j                  |      }d}| j                  dj                  | j                  j                  d            d       ||fS # t        $ rD}| j                  d	j                  | j                  j                  d            d
       Y d}~d}~ww xY w)a|  
        Check if the site exists in Cisco Catalyst Center.

        Parameters:
          - self (object): An instance of the class containing the method.
        Returns:
          - tuple: A tuple containing a boolean indicating whether the site exists and
                   a dictionary containing information about the existing site.
                   The returned tuple includes two elements:
                   - site_exists (bool): Indicates whether the site exists.
                   - dict: Contains information about the existing site. If the
                           site doesn't exist, this dictionary is empty.
        Description:
            Checks the existence of a site in Cisco Catalyst Center by querying the
          'get_site' function in the 'sites' family. It utilizes the
          'site_name' parameter from the 'want' attribute to identify the site.
        FNsitesget_siteTrA   	site_namefamilyfunctionop_modifiesparamsz[The provided site name '{0}' is either invalid or not present in the Cisco Catalyst Center.WARNINGresponsez*Received API response from 'get_site': {0}DEBUGz*Site '{0}' exists in Cisco Catalyst Centerr-   )	dnac_execwantrW   	Exceptionr1   r4   r$   r`   )r   site_existsr_   rk   es        r   rq   zDnacSite.site_exists  s   & 
	Eyy# 		k :;	 ' H ||J/HHHAHHXWY`a00:LKHHAHHWbIcdflm\**  	EHHrfTYY]];78)E E	Es   :C 	D:DDc           	         |j                  d      }i }|dvrId| _        dj                  |      | _        | j	                  | j                  d       | j                          |dk(  rH|j                  d      j                  d      }|j                  d      |j                  d	      d
|d<   n+|dk(  r|j                  d      j                  d      }|j                  d      |j                  d      |j                  d	      |j                  d      |j                  d      |j                  d      d|d<   n|j                  d      j                  d      }|j                  d      |j                  d	      |j                  d      |j                  d      |j                  d      |j                  dd      d|d<   	 |j                  d      |d   d<   t        ||      }| j	                  dj                  t        |            d       |S # t        $ r:}| j	                  dj                  |j                  d            d       Y d}~wd}~ww xY w) a?  
        Store the site-related parameters.

        Parameters:
          self (object): An instance of a class used for interacting with Cisco Catalyst Center.
          - params (dict): Dictionary containing site-related parameters.
        Returns:
          - dict: Dictionary containing the stored site-related parameters.
                  The returned dictionary includes the following keys:
                  - 'type' (str): The type of the site.
                  - 'site' (dict): Dictionary containing site-related info.
        Description:
            This method takes a dictionary 'params' containing site-related
          information and stores the relevant parameters based on the site
          type. If the site type is 'floor', it ensures that the 'rfModel'
          parameter is stored in uppercase.
        r'   )r@   rF   rK   r,   zjInvalid site type '{0}' given in the playbook. Please select one of the type - 'area', 'building', 'floor'r#   r@   r*   rA   parent_namerD   rF   rG   rH   rI   rJ   )rA   rG   rE   rH   rI   rJ   rK   rP   rO   rQ   floor_number )rA   rE   rP   rO   rQ   rT   rS   rN   z3The attribute 'rf_model' is missing in floor '{0}'.rj   Nr)   zSite parameters: {0}rl   )	rW   r/   r4   r0   r1   check_return_statusrp   r(   r$   )	r   ri   r\   rZ   area_detailsbuilding_detailsfloor_detailsrr   site_paramss	            r   get_site_paramszDnacSite.get_site_params  sJ   $ ::f%	88"DK D  K  K  LT  UDHHHTXXw'$$&v!::f-11&9L$((0*..}=!If #%zz&155jA(,,V4+//	:.22=A,00<-11+>+//	:%Ij! #JJv.227;M%))&1+//>'++H5&**73'++H5,00D"Ig}0=0A0A*0M	'"9- 
 	'..s;/?@'J  }NUUVcVgVghnVopr{||}s   H 	I0IIc                 L   |j                  d      }|j                  d      j                  |      j                  d      }|j                  d      j                  |      j                  d      }dj                  ||g      }| j                  dj                  |      d       |S )a  
        Get and Return the site name.
        Parameters:
          - self (object): An instance of a class used for interacting with Cisco Catalyst Center.
          - site (dict): A dictionary containing information about the site.
        Returns:
          - str: The constructed site name.
        Description:
            This method takes a dictionary 'site' containing information about
          the site and constructs the site name by combining the parent name
          and site name.
        r'   r*   rt   rA   rC   zSite name: {0}r-   )rW   r5   r1   r4   )r   r*   	site_typert   rA   rd   s         r   get_site_namezDnacSite.get_site_name9  s     HHV$	hhv&**9599-Hxx##I.226:HHk401	!((3V<r    c                 X    t        t        |      |      t        t        |      |      k(  S )a|  
        Compare two floating-point values with a specified precision.
        Args:
            - self (object): An instance of a class used for interacting with Cisco Catalyst Center.
            - ele1 (float): The first floating-point value to be compared.
            - ele2 (float): The second floating-point value to be compared.
            - precision (int, optional): The number of decimal places to consider in the comparison, Defaults to 2.
        Return:
            bool: True if the rounded values are equal within the specified precision, False otherwise.
        Description:
            This method compares two floating-point values, ele1 and ele2, by rounding them
            to the specified precision and checking if the rounded values are equal. It returns
            True if the rounded values are equal within the specified precision, and False otherwise.
        )roundfloat)r   ele1ele2	precisions       r   compare_float_valueszDnacSite.compare_float_valuesO  s%      U4[),eDk90MMMr    c                 2    |d   |d   k(  xr |d   |d   k(  S )a  
        Check if the area site details have been updated.
        Args:
            - self (object): An instance of a class used for interacting with Cisco Catalyst Center.
            - updated_site (dict): The site details after the update.
            - requested_site (dict): The site details as requested for the update.
        Return:
            bool: True if the area details (name and parent name) have been updated, False otherwise.
        Description:
            This method compares the area details (name and parent name) of the updated site
            with the requested site and returns True if they are equal, indicating that the area
            details have been updated. Returns False if there is a mismatch in the area site details.
        rA   rE    r   updated_siterequested_sites      r   is_area_updatedzDnacSite.is_area_updateda  s3       N6$:: G&.*FF	
r    c                     |d   |d   k(  xrg |d   |d   k(  xrZ | j                  |d   |d         xr@ | j                  |d   |d         xr& d|v xr  |d   du xs |j                  d      |d   k(  S )a%  
        Check if the building details in a site have been updated.
        Args:
            - self (object): An instance of a class used for interacting with Cisco Catalyst Center.
            - updated_site (dict): The site details after the update.
            - requested_site (dict): The site details as requested for the update.
        Return:
            bool: True if the building details have been updated, False otherwise.
        Description:
            This method compares the building details of the updated site with the requested site.
            It checks if the name, parent_name, latitude, longitude, and address (if provided) are
            equal, indicating that the building details have been updated. Returns True if the
            details match, and False otherwise.
        rA   rE   rH   rI   rG   N)r   rW   r   s      r   is_building_updatedzDnacSite.is_building_updatedu  s    "  N6$:: N&.*FFN%%l:&>z@Z[N %%l;&?P[A\]N .(  MnY.G4.O  /LS_ScScdmSn  sA  BK  sL  TL	
r    c                     g d}|d   |d   k7  s#|j                  d      |j                  d      k7  ry|D ]  }| j                  ||   ||         r y y)a  
        Check if the floor details in a site have been updated.

        Args:
            - self (object): An instance of a class used for interacting with Cisco Catalyst Center.
            - updated_site (dict): The site details after the update.
            - requested_site (dict): The site details as requested for the update.
        Return:
            bool: True if the floor details have been updated, False otherwise.
        Description:
            This method compares the floor details of the updated site with the requested site.
            It checks if the name, rf_model, length, width, and height are equal, indicating
            that the floor details have been updated. Returns True if the details match, and False otherwise.
        )rP   rO   rQ   rA   rS   rN   FT)rW   r   )r   r   r   keys_to_comparekeys        r   is_floor_updatedzDnacSite.is_floor_updated  sn      8>&#99\=M=Mj=Y]k]o]opy]z=z" 	C,,\#->s@ST	 r    c                    | j                   d   d   }| j                   d   d   |   }| j                  d   d   |   }| j                  dj                  t	        |            d       | j                  dj                  t	        |            d       |dk(  r| j                  ||       S |d	k(  r| j                  ||       S | j                  ||       S )
aF  
        Check if the site requires updates.
        Parameters:
            self (object): An instance of a class used for interacting with Cisco Catalyst Center.
        Returns:
            bool: True if the site requires updates, False otherwise.
        Description:
            This method compares the site parameters of the current site
            ('current_site') and the requested site parameters ('requested_site')
            stored in the 'want' attribute. It checks for differences in
            specified parameters, such as the site type and site details.
        r_   r'   r*   r{   zCurrent Site type: {0}r-   zRequested Site type: {0}rF   rK   )havero   r1   r4   r$   r   r   r   )r   r'   r   r   s       r   site_requires_updatezDnacSite.site_requires_update  s     yy(0yy08>=1&9$?)00\1BCVL+223~3FGP://nMMMW_,,\>JJJ''nEEEr    c                 B   d}d}i }| j                         \  }}| j                  dj                  t        |            d       |r|j	                  d      |d<   ||d<   ||d<   || _        | j                  d	j                  t        | j
                              d
       | S )a  
        Get the site details from Cisco Catalyst Center
        Parameters:
          - self (object): An instance of a class used for interacting with Cisco Catalyst Center.
          - config (dict): A dictionary containing the configuration details.
        Returns:
          - self (object): An instance of a class used for interacting with  Cisco Catalyst Center.
        Description:
            This method queries Cisco Catalyst Center to check if a specified site
            exists. If the site exists, it retrieves details about the current
            site, including the site ID and other relevant information. The
            results are stored in the 'have' attribute for later reference.
        FNz Current Site details (have): {0}rl   rV   site_idrq   r_   Current State (have): {0}r-   )rq   r1   r4   r$   rW   r   )r   r.   rq   r_   r   s        r   get_havezDnacSite.get_have  s      '+&6&6&8#l3::3|;LMwW*..x8DO"-D#/D 	,33C		NCVLr    c                     i }t        | j                  |      | j                  |            }|| _        | j	                  dj                  t        | j                              d       | S )a  
        Get all site-related information from the playbook needed for creation/updation/deletion of site in Cisco Catalyst Center.
        Parameters:
            self (object): An instance of a class used for interacting with Cisco Catalyst Center.
            config (dict): A dictionary containing configuration information.
        Returns:
            self (object): An instance of a class used for interacting with Cisco Catalyst Center.
        Description:
            Retrieves all site-related information from playbook that is
            required for creating a site in Cisco Catalyst Center. It includes
            parameters such as 'site_params' and 'site_name.' The gathered
            information is stored in the 'want' attribute for later reference.
        )r{   rd   Desired State (want): {0}r-   )r(   r|   r   ro   r1   r4   r$   )r   r.   ro   s      r   get_wantzDnacSite.get_want  s_     ,,V4((0
 	,33C		NCVLr    c                 N   d}d}| j                   j                  d      }| j                  j                  d      r| j                         r| j                   j                  d      }| j                  j                  d      |d<   | j                  j                  ddd|	      }| j                  d
j                  t        |            d       d}n| j                  j                  |       | j                  dj                  |      d       | S | j                   j                  d      }	 |d   d   r0i }|d   d   j                         D ]  \  }}	|		|	||<    ||d   d<   | j                  j                  ddd|	      }| j                  dj                  t        |            d       d}|s|r+|r(t        |t              r|j                  d      }	 | j                  |      }|j                  d      dk(  rd| j                   d<   n?|j                  d      r-| j"                  j%                  |j                  d      |       nt|r>| j&                  j                  |       | j                  dj                  |      d       | S | j)                         \  }}|r<| j*                  j                  |       | j                  dj                  |      d       | S # t        $ r<}
|d   }|d   |   d   }| j                  dj                  |      d       Y d}
~
d}
~
ww xY w)a  
        Update/Create site information in Cisco Catalyst Center with fields
        provided in the playbook.
        Parameters:
          self (object): An instance of a class used for interacting with Cisco Catalyst Center.
          config (dict): A dictionary containing configuration information.
        Returns:
            self (object): An instance of a class used for interacting with Cisco Catalyst Center.
        Description:
            This method determines whether to update or create a site in Cisco Catalyst Center based on the provided
            configuration information. If the specified site exists, the method checks if it requires an update
            by calling the 'site_requires_update' method. If an update is required, it calls the 'update_site'
            function from the 'sites' family of the Cisco Catalyst Center API. If the site does not require an update,
            the method exits, indicating that the site is up to date.
        Frd   rq   r{   r   rb   update_siteTre   z-Received API response from 'update_site': {0}rl   z#Site - {0} does not need any updater-   r*   rF   Nr'   rA   zThe site '{0}' is not categorized as a building; hence, there is no need to filter out 'None'
                            values from the 'site_params' dictionary.create_sitez-Received API response from 'create_site': {0}executionIdr/   SUCCESSchanged	bapiErrorr0   rk   zSite - {0} Updated SuccessfullyzSite '{0}' created successfully)ro   rW   r   r   rm   rn   r1   r4   r$   r   appenditemsrp   
isinstancer(   get_execution_detailsresultr   	fail_jsonr   rq   r   )r   r.   site_updatedsite_createdrd   r{   rk   ry   r   valuerr   r~   rA   executionidexecution_detailsrq   r_   s                    r   get_diff_mergedzDnacSite.get_diff_merged  s!   " IIMM+.	 99=='((*"iimmM:)-y)AI&99??"* $&	 +  HOOPST\P]^`gh# --44Y?>EEiPRXY ))--6K_v&z2')$&1&&9*&E&K&K&M :
U ,49,S1: 7GK'
3 yy& "	 ' H HHDKKCPXMZ\cdL<Jx6&ll=9(,(B(B;(O%(,,X6)C15I.*..{;--2C2G2G2T7H . J   **11)<HH>EEiPRXY  372B2B2D/[,"..55i@!B!I!I)!TV\]Q  _'/	"6*95f= IIOPTW]_ __s   *(K K 	L$(1LL$c                 V   	 | j                   j                  dddd|i      }|r)t        |t              r| j	                  dj                  t        |            d       |j                  d      }	 | j                  |      }|j                  d	      d
k(  rFd| _	        | j                  j                  |       | j	                  dj                  |      d       	 | S |j                  d      r_| j	                  dj                  |j                  d            d       | j                  j                  |j                  d      |       	 | S | S # t        $ rN}d| _	        dj                  |t        |            | _        | j	                  | j                  d       Y d}~| S d}~ww xY w)a;  "
        Delete a single site in the Cisco Catalyst Center.
        Parameters:
            self (object): An instance of a class used for interacting with Cisco Catalyst Center.
            site_id (str): The ID of the site to be deleted.
            site_name (str): The name of the site to be deleted.
        Returns:
            self (object): An instance of a class used for interacting with Cisco Catalyst Center.
        Description:
            This function initiates the deletion of a site in the Cisco Catalyst Center by calling the delete API.
            If the deletion is successful, the result is marked as changed, and the status is set to "success."
            If an error occurs during the deletion process, the status is set to "failed," and the log contains
            details about the error.
        rb   delete_siteTr   re   z-Received API response from 'delete_site': {0}rl   r   r/   r   r"   zSite '{0}' deleted successfullyr-   r   z/Error response for 'delete_site' execution: {0}r#   r   r,   z8Exception occurred while deleting site '{0}' due to: {1}N)rm   rn   r   r(   r1   r4   r$   rW   r   r/   r   r   r   r   rp   r0   )r   r   rd   rk   r   r   rr   s          r   delete_single_sitezDnacSite.delete_single_site]  s    	(yy& !7+	 ' H Jx6HOOPST\P]^`gh&ll=9(,(B(B;(O%(,,X6)C&/..55i@!B!I!I)!TV\]  +..{;!R!Y!YZkZoZop{Z|!}  @G  H--2C2G2G2T_p-q # "   	("DKQXXYbdghidjkDHHHTXXw''	(s&   CE A-E E 	F(AF##F(c                 h   | j                   j                  d      }| j                  j                  d      }|sEd| _        | j                  j                  |       | j                  dj                  |      d       | S | j                   j                  d      }| j                  j                  ddd	d|i
      }| j                  dj                  t        |            d       |j                  d      j                  d      }| j                  dj                  |t        |            d       t        |      dk(  r| j                  ||       | S t        |d d	      }|D ]  }| j                  |d   |d           | j                  ||       | j                  dj                  |      d       | S )a  
        Call Cisco Catalyst Center API to delete sites with provided inputs.
        Parameters:
          - self (object): An instance of a class used for interacting with Cisco Catalyst Center.
          - config (dict): Dictionary containing information for site deletion.
        Returns:
          - self: The result dictionary includes the following keys:
              - 'changed' (bool): Indicates whether changes were made
                 during the deletion process.
              - 'response' (dict): Contains details about the execution
                 and the deleted site ID.
              - 'msg' (str): A message indicating the status of the deletion operation.
        Description:
            This method initiates the deletion of a site by calling the 'delete_site' function in the 'sites' family
            of the Cisco Catalyst Center API. It uses the site ID obtained from the 'have' attribute.
        rq   rd   r"   zFUnable to delete site '{0}' as it's not found in Cisco Catalyst Centerr-   r   rb   get_membershipTre   z0Received API response from 'get_membership': {0}rl   r*   rk   z2Site {0} response along with it's child sites: {1}r   c                 $    | j                  d      S )NgroupHierarchy)rW   )xs    r   <lambda>z+DnacSite.get_diff_deleted.<locals>.<lambda>  s    quuEU?V r    )r   reverserU   rA   zAThe site '{0}' and its child sites have been deleted successfully)r   rW   ro   r/   r   r   r1   r4   rm   rn   r$   lenr   sorted)	r   r.   rq   rd   r   mem_responsesite_responsesorted_site_respitems	            r   get_diff_deletedzDnacSite.get_diff_deleted  s   $ iimmM2IIMM+.	#DK!!((3HH]ddenoqwxK ))--	*yy%w'	 ' 
 	CJJ3|K\]_fg$((044Z@ELLYX[\iXjkmtu}"##GY7K "-5V`de % 	>D##DJV=	> 	3T[[\efhnor    c                    | j                  |       | j                  dj                  t        | j                              d       | j                  dj                  t        | j
                              d       | j                  j                  d      }| j
                  j                  d      }|r9d| _        dj                  |      | _        | j                  | j                  d       | j                         }|s*| j                  dj                  |      d       d| _        | S | j                  d	j                  |      d       | S )
a  
        Verify the merged status(Creation/Updation) of site configuration in Cisco Catalyst Center.
        Args:
            - self (object): An instance of a class used for interacting with Cisco Catalyst Center.
            - config (dict): The configuration details to be verified.
        Return:
            - self (object): An instance of a class used for interacting with Cisco Catalyst Center.
        Description:
            This method checks the merged status of a configuration in Cisco Catalyst Center by retrieving the current state
            (have) and desired state (want) of the configuration, logs the states, and validates whether the specified
            site exists in the Catalyst Center configuration.
        r   r-   r   rq   rd   r"   zdThe requested site '{0}' is present in the Cisco Catalyst Center and its creation has been verified.z9The update for site '{0}' has been successfully verified.zThe playbook input for site '{0}' does not align with the Cisco Catalyst Center, indicating that the merge task
                 may not have executed successfully.)
r   r1   r4   r$   r   ro   rW   r/   r0   r   )r   r.   
site_existrd   require_updates        r   verify_diff_mergedzDnacSite.verify_diff_merged  s    	f,33C		NCVL,33C		NCVL YY]]=1
IIMM+.	#DK}  E  E  FO  PDHHHTXXv&224HHPWWXabdjk$DLK 88>y8I6	S r    c                 0   | j                  |       | j                  dj                  t        | j                              d       | j                  dj                  t        | j
                              d       | j                  j                  d      }|sEd| _        dj                  | j
                  j                  d            }| j                  |d       | S | j                  dj                  | j
                  j                  d            d       | S )	aa  
        Verify the deletion status of site configuration in Cisco Catalyst Center.
        Args:
            - self (object): An instance of a class used for interacting with Cisco Catalyst Center.
            - config (dict): The configuration details to be verified.
        Return:
            - self (object): An instance of a class used for interacting with Cisco Catalyst Center.
        Description:
            This method checks the deletion status of a configuration in Cisco Catalyst Center.
            It validates whether the specified site exists in the Catalyst Center configuration.
        r   r-   r   rq   r"   zThe requested site '{0}' has already been deleted from the Cisco Catalyst Center and this has been
                successfully verified.rd   zMismatch between the playbook input for site '{0}' and the Cisco Catalyst Center indicates that
                 the deletion was not executed successfully.)r   r1   r4   r$   r   ro   rW   r/   )r   r.   r   r0   s       r   verify_diff_deletedzDnacSite.verify_diff_deleted  s     	f,33C		NCVL,33C		NCVL YY]]=1
#DK**0&{1K*L HHS&!K @@Ftyy}}U`Ga@bdj	l r    c                    | j                   r| j                  rd| j                  d<   | j                  rUd}|j	                  t        | j                         t        | j                        t        | j                              | _        ndj	                  t        | j                         t        | j                              | _        nI| j                   rd| j                  d<   | j                  r?dj	                  t        | j                         t        | j                              | _        ndj	                  t        | j                               | _        n| j                  rd| j                  d<   | j                  r?dj	                  t        | j                        t        | j                              | _        nRdj	                  t        | j                              | _        n'| j                  r9d	| j                  d<   d
j	                  t        | j                              | _        n| j                  rY| j                  rMd| j                  d<   dj	                  t        | j                        t        | j                              | _        n}| j                  r9d| j                  d<   dj	                  t        | j                              | _        n8d	| j                  d<   dj	                  t        | j                              | _        d| _	        | j                  | j                  d<   | j                  | j                  d<   | S )a4  
        Update site messages based on the status of created, updated, and deleted sites.
        Args:
            self (object): An instance of a class used for interacting with Cisco Catalyst Center.
        Returns:
            self (object): An instance of a class representing the status of the operation, including whether it was
                successful or failed, any error messages encountered during operation.
        Description:
            This method updates the messages related to site creation, updating, and deletion in the Cisco Catalyst Center.
            It evaluates the status of created sites, updated sites, and sites that are no longer needed for update to
            determine the appropriate message to be set. The messages are then stored in the 'msg' attribute of the object.
        Tr   zSite(s) '{0}' created successfully as well as Site(s) '{1}' updated successully and the some site(s)
                        '{2}' needs no update in Cisco Catalyst CenterzSite(s) '{0}' created successfully in Cisco Catalyst Center as well as Site(s) '{1}' updated successully in
                        Cisco Catalyst CenterzSite(s) '{0}' created successfully and some site(s) '{1}' not needs any update in Cisco Catalyst
                                Center.z<Site(s) '{0}' created successfully in Cisco Catalyst Center.zSite(s) '{0}' updated successfully and some site(s) '{1}' not needs any update in Cisco Catalyst
                                Center.z<Site(s) '{0}' updated successfully in Cisco Catalyst Center.Fz<Site(s) '{0}' not needs any update in Cisco Catalyst Center.zGiven site(s) '{0}' deleted successfully from Cisco Catalyst Center and unable to deleted some site(s) '{1}' as they
                    are not found in Cisco Catalyst Center.zCGiven site(s) '{0}' deleted successfully from Cisco Catalyst CenterzJUnable to delete site(s) '{0}' as it's not found in Cisco Catalyst Center.r"   rk   r0   )
r   r   r   r   r4   r$   r0   r   r   r/   )r   r0   s     r   update_site_messageszDnacSite.update_site_messages
  s    !!d&<&<%)DKK	",,J::c$*@*@&A3tG]G]C^`cdh  eB  eB  aC  D117D<R<R8SUXY]YoYoUp1q ##%)DKK	",,++16#d6L6L2MsSWSpSpOq+r  Z``adeie{e{a|}##%)DKK	",,++16#d6L6L2MsSWSpSpOq+r  Z``adeie{e{a|}**%*DKK	"U\\]`aea~a~]  ADH##(=(=%)DKK	"??Evc$J`J`Facfgkg|g|c}?~ H##%)DKK	"\ccdghlh~h~d  ADH%*DKK	"cjjknos  pE  pE  lF  GDH"&((J!XXEr    )   )__name__
__module____qualname____doc__r   r:   r`   rq   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   r   __classcell__)r   s   @r   r   r   L  ss    C?2hBH(+T@D,N$
(
04F8 D2]~-^6p%N>7r    r   c                     i ddddddddddd	d
gdddddddddddddddddddddddddddddddddddddddddddddd dd!dd"dd#d$d%d&d'd'd(gd)} t        | d*      }t        |      }|j                  j                  d&      }||j                  vr-d+|_        d,j                  |      |_        |j                          |j                         j                          |j                  j                  d      }|j                  D ]  }|j                          |j                  |      j                          |j                  |      j                           |j                  |   |      j                          |sw |j                  |   |      j                           |j!                         j                           |j"                  d.i |j$                   y-)/z+ main entry point for module execution
    	dnac_hostTr$   r%   	dnac_port443)r'   defaultdnac_usernameadminuser)r'   r   aliasesdnac_password)r'   no_logdnac_verifyboolTruednac_versionz2.2.3.3
dnac_debugFdnac_log_levelrj   dnac_log_file_pathzdnac.logdnac_log_appenddnac_logvalidate_response_schemaconfig_verifydnac_api_task_timeoutinti  dnac_task_poll_intervalr   r.   listr(   )r&   r'   elementsstater   r   )r   choices)argument_specsupports_check_modeinvalidzState {0} is invalidNr   )r   r   ri   rW   r   r/   r4   r0   rw   r:   r6   reset_valuesr   r   get_diff_state_applyverify_diff_state_applyr   	exit_jsonr   )element_specr   	dnac_siter   r   r.   s         r   mainr   D  s   KdE!B %E!B#eU[T\%] $et%D "Fv#F	
 #Uy$I !6e"D %u&K )5Z*P &4'H E B /D0Q $f%G ,e-M .!/L 4VT  x>ST!L& /46F  I  )EI...$	.55e<	%%'224$$((9M,, S 6"6686"668-	&&u-f5IIK4I--e4V<PPRS ""$88:F(y''(r    __main__N)
__future__r   r   r   r'   __metaclass__
__author__DOCUMENTATIONEXAMPLESRETURNansible.module_utils.basicr   8ansible_collections.cisco.dnac.plugins.module_utils.dnacr   r   r	   rY   r   r   r   r   r    r   <module>r      s   
 A @O
BFfNH
T 5  )##"
ux up0)f zF r    