o
    /^id                     @   s  d Z ddlZddlmZ ddlmZ dedefddZded	efd
dZ	deded	efddZ
dededededef
ddZdededefddZdedededededefddZdedefddZdedefddZdedefdd Zdefd!d"Zdedefd#d$ZdS )%aH  
Settings Tab UI

This module provides the UI for managing application settings,
specifically MongoDB connection configuration.

Key principles:
- Manual control: All actions require explicit user confirmation
- Clear feedback: Success and error messages are always shown
- No automation: No background reconnections or retries
    N)SettingsService)MongoServicesettings_servicemongo_servicec                 C   s   t d t d t d t d |  }t|| t d t| || t d t d t d t| | t d t d t d t|  dS )z
    Render the Settings tab with MongoDB configuration.
    
    Args:
        settings_service: Settings service instance
        mongo_service: MongoDB service instance
    u   ⚙️ Settingsz6Configure MongoDB connection and application settings.---u    🔌 MongoDB Connection Settingsu   📋 Collection Configurationu   ⚙️ Data Loading SettingsN)	sttitlemarkdownheaderget_mongodb_settings_render_connection_status_render_configuration_form _render_collection_configuration_render_record_limit_settings)r   r   current_settings r   ,/var/www/html/IGF-ODF-V3/ui/tabs/settings.pyrender_settings_tab   s    












r   r   c                 C   s   t d t d\}}|% |  rt d nt d |  }|r,t d|  W d   n1 s6w   Y  | t d|d  d	 W d   n1 sSw   Y  |d
 }t|}t 	d|  dS )z
    Render current connection status.
    
    Args:
        mongo_service: MongoDB service instance
        current_settings: Current MongoDB settings
    u   📊 Current Connection Status   u   ✅ **Status:** Connectedu   ❌ **Status:** Not Connected**Error:** Nz**Active Database:** `database`urizConnection URI: )
r   	subheadercolumnsis_connectedsuccesserrorget_connection_errorinfo	_mask_uritext)r   r   col1col2r   r   
masked_urir   r   r   r   <   s"   

	r   c              
   C   s  t d t d t d t d t jd|d r |d nddd	dd
}t jd|d ddd}t d t d\}}| t jddd|d ddd}W d   n1 sXw   Y  | t jddd|d ddd}W d   n1 sww   Y  t d t g d\}}}	| t jddd }
W d   n1 sw   Y  | t jd!d"d }W d   n1 sw   Y  W d   n1 sw   Y  |
rt| |||| |r||||d#t j	_
t   d$t j	v rt| |t j	j
 dS dS )%z
    Render the configuration form for MongoDB settings.
    
    Args:
        settings_service: Settings service instance
        mongo_service: MongoDB service instance
        current_settings: Current MongoDB settings
    u   🔧 Configurationz
    **Important:**
    - Changes will be saved to `app_config.yaml`
    - The MongoDB URI will be stored in the environment variable
    - You must click "Save Settings" to apply changes
    - After saving, the application will attempt to reconnect
    mongodb_settings_formz### Connection DetailszMongoDB URIr   zpmongodb://AdminUser:WnE0TjGIafVJutreZL7cTIoWNWU52YyxLVgwCUqIGCGg3YUT@18.184.249.241:27017/?authMechanism=DEFAULTpasswordzEFull MongoDB connection string (e.g., mongodb://user:pass@host:port/))valuetypehelpplaceholderzDatabase Namer   z#Name of the MongoDB database to useIGF_WORK)r'   r)   r*   z#### Timeout Settings (milliseconds)r   zConnection Timeout  i`  connection_timeoutz#Time to wait for initial connection	min_value	max_valuer'   stepr)   NzServer Selection Timeoutserver_selection_timeoutz!Time to wait for server selectionr   )   r3   r   u   🧪 Test Connection	secondaryr(   u   💾 Save Settingsprimary)r   r   r-   r2   pending_settings)r   r   r	   form
text_inputr   number_inputform_submit_button_handle_test_connectionsession_stater7   rerun_show_save_confirmation)r   r   r   r   r   r"   r#   r-   r2   col3test_buttonsave_buttonr   r   r   r   Z   s   

	
	



>	

r   r   r   r-   r2   c                 C   s   t d | ||||\}}W d   n1 sw   Y  |r1t d t d| d dS t d t d|  t d dS )	a  
    Handle test connection action.
    
    Args:
        settings_service: Settings service instance
        uri: MongoDB URI
        database: Database name
        connection_timeout: Connection timeout in ms
        server_selection_timeout: Server selection timeout in ms
    zTesting connection...Nu#   ✅ **Connection test successful!**z%Successfully connected to database: `r   u   ❌ **Connection test failed!**r   z4Please check your connection settings and try again.)r   spinnertest_connectionr   r   r   warning)r   r   r   r-   r2   r   r   r   r   r   r<      s   


r<   r7   c              	   C   s  t d t d t d|d  d|d  d|d  d	 t d
\}}|% t jdddddrFt| ||d |d |d |d  t j`W d   n1 sPw   Y  |% t jddddrtt j`t d t 	  W d   dS W d   dS 1 sw   Y  dS )z
    Show confirmation dialog for pending settings.
    
    Args:
        settings_service: Settings service instance
        mongo_service: MongoDB service instance
        pending_settings: Dictionary with pending settings
    r   u"   ⚠️ **Confirm Settings Change**zS
    You are about to update the MongoDB connection settings:
    - **Database:** `r   z `
    - **Connection Timeout:** r-   z'ms
    - **Server Selection Timeout:** r2   zms
    
    This will:
    1. Save settings to `app_config.yaml`
    2. Update the environment variable for this session
    3. Require a manual reconnection
    r   u   ✅ Confirm SaveTr6   confirm_save_btn)use_container_widthr(   keyr   Nu
   ❌ Cancelcancel_save_btn)rG   rH   z%Save cancelled. No changes were made.)
r   r	   rE   r   button_execute_saver=   r7   r   r>   )r   r   r7   r"   r#   r   r   r   r?      s>   


	

"r?   c           	      C   sB  t d | ||||\}}W d   n1 sw   Y  |rt d t d |   t d t jdddd	rt d
 |d|_	|
 }W d   n1 sVw   Y  |rqt d t d t   t   dS t d | }|rt d|  t d dS dS t d t d|  t d dS )aG  
    Execute the save operation.
    
    Args:
        settings_service: Settings service instance
        mongo_service: MongoDB service instance
        uri: MongoDB URI
        database: Database name
        connection_timeout: Connection timeout in ms
        server_selection_timeout: Server selection timeout in ms
    zSaving settings...Nu$   ✅ **Settings saved successfully!**z-Settings have been saved to `app_config.yaml`z
        **Next Steps:**
        1. The application needs to reconnect with the new settings
        2. Click the button below to reconnect
        3. Check the connection status in the sidebar
        u   🔄 Reconnect Nowr6   reconnect_btn)r(   rH   zReconnecting to MongoDB...zconfig/app_config.yamlu!   ✅ **Reconnected successfully!**z,MongoDB connection updated with new settingsu   ❌ **Reconnection failed!**r   z)Please check your settings and try again.u    ❌ **Failed to save settings!**z*Please verify your settings and try again.)r   rC   save_mongodb_settingsr   r   reload_configrE   rJ   _load_configconfigconnectballoonsr>   r   r   )	r   r   r   r   r-   r2   r   r   reconnect_successr   r   r   rK   "  s@   








rK   returnc                 C   sf   | sdS d| v r1|  d}d|d v r|d  dd nd}t|dkr(|d nd}| d| S | S )	z
    Mask sensitive parts of MongoDB URI.
    
    Args:
        uri: MongoDB connection URI
    
    Returns:
        Masked URI string
    zNot configured@z//r   zmongodb:r3   unknownz
//***:***@)splitlen)r   partsprotocol_part	host_partr   r   r   r    d  s   

"r    c                 C   sV   t d |  }|st d dS t| }t jd|dd}|r)t| | dS dS )z
    Render collection configuration section.
    
    Args:
        settings_service: Settings service instance
        mongo_service: MongoDB service instance
    z
    Configure business keys, alternative keys, and matching strategies for each collection.
    This determines how duplicate records are detected during import.
    u%   ℹ️ No collections configured yet.NzSelect Collection to Configurez-Choose which collection you want to configure)r)   )r   r	   get_all_collectionsr   listkeys	selectbox_render_collection_editor)r   r   collectionscollection_namesselected_collectionr   r   r   r   }  s   

r   collection_namec                 C   sV  |  |}td|  td|  td td |dg }tjdd|dd	d
d}td td |dg }tjdd|dddd}td |dd}tjdg dg d	|dd}tj
d|dddd}	td tjdd d!}
|
rd"d# |dD }d$d# |dD }|s|d%krtd& 	 W d'   d'S |s|d(v rtd) 	 W d'   d'S | |||||	\}}|rtd*|  td+d,| d- d,| d. | d/ t|	 d0  t  ntd1|  W d'   n	1 sw   Y  td td2 td3\}}|$ td4 |r<|D ]}td5|  q/ntd6 W d'   n	1 sLw   Y  |$ td7 |rk|D ]}td5|  q^ntd6 W d'   n	1 s{w   Y  td8| d9 td:|ddrd;nd<  td td= t| | d'S )>z
    Render editor for a specific collection.
    
    Args:
        settings_service: Settings service instance
        collection_name: Name of the collection to edit
    u   ⚙️ Configure: collection_config_z### Business Keys (Primary)zFFields used to identify unique records. Enter one field name per line.business_keyszBusiness Keys
d   z3Example: code, athlete_id, player_id (one per line)zcode
athlete_id)r'   heightr)   r*   z ### Alternative Keys (Secondary)znAdditional fields used when primary keys don't match. Useful for finding the same person with different codes.alternative_keyszAlternative Keysz;Example: given_name, family_name, birth_date (one per line)z!given_name
family_name
birth_datez### Matching Strategymatching_strategyprimary_onlyzMatching Strategy)rl   primary_or_alternativealternative_onlyz
            - primary_only: Match only by business keys
            - primary_or_alternative: Try business keys first, then alternative keys
            - alternative_only: Match only by alternative keys
            )indexr)   zCollection EnabledenabledTz!Enable or disable this collection)r'   r)   r   u"   💾 Save Collection Configurationr6   r5   c                 S      g | ]
}|  r|  qS r   strip.0kr   r   r   
<listcomp>      z-_render_collection_editor.<locals>.<listcomp>c                 S   rq   r   rr   rt   r   r   r   rw     rx   rn   uG   ❌ Business keys are required unless using 'alternative_only' strategyN)rm   rn   u<   ❌ Alternative keys are required for this matching strategyu(   ✅ Configuration saved for collection: zM
                **Configuration updated:**
                - Business Keys: z, z%
                - Alternative Keys: z&
                - Matching Strategy: z
                - Enabled: un   
                
                💡 Changes will take effect on the next import operation.
                u"   ❌ Failed to save configuration: z### Current Configurationr   z**Business Keys:**     • z  (none)z**Alternative Keys:**z**Matching Strategy:** `r   z**Enabled:** u   ✅ Yesu   ❌ Noz### Foreign Key Relationships)get_collection_configr   r   r8   r	   get	text_areajoinr_   ro   checkboxr;   rW   r   update_collection_configr   r   strrR   r   r!   _render_foreign_key_editor)r   rd   rP   current_business_keysbusiness_keys_textcurrent_alternative_keysalternative_keys_textcurrent_strategyrk   rp   	submittedrf   rj   r   r   r"   r#   rH   r   r   r   r`     s   
	







C
H
	
`




"

r`   c              	   C   s0  t d |  }t d|dd t dv t d t jddd	|d
dd}t d t d t jddd}|rv||krFt d n8| |\}}|rft d|dd|d t d t 	  n t 
d|  W d   dS W d   dS W d   dS W d   dS 1 sw   Y  dS )zr
    Render record limit settings section.
    
    Args:
        settings_service: Settings service instance
    a1  
    Configure the maximum number of records to load from MongoDB when comparing with JSON files.
    
    **Important:** If your collection has more records than this limit, only the first N records will be loaded for comparison.
    This may cause duplicate detection to miss some existing records.
    u   📊 Current record limit: **,z
** recordsrecord_limit_formz### Set Record LimitzMaximum Records to Loadrh   i r,   zENumber of records to load from MongoDB for comparison (100 - 100,000)r.   u`  
        **Recommendations:**
        - **Small collections (<1,000 records):** Use 5,000
        - **Medium collections (1,000-10,000 records):** Use 10,000-20,000
        - **Large collections (>10,000 records):** Use 50,000-100,000
        
        ⚠️ **Warning:** Higher limits use more memory and may slow down the comparison process.
        r   u   💾 Save Record Limitr6   r5   u   ℹ️ Record limit unchangedu   ✅ Record limit updated:     → uE   💡 The new limit will be used for all future comparison operations.u#   ❌ Failed to update record limit: N)r   r	   get_record_limitr   r8   r:   r;   update_record_limitr   rR   r   )r   current_limit	new_limitr   r   r   r   r   r   r   (  sF   


	
	

%"r   c                 C   sZ  t d | |}t|   }t d| W t d t d t jddd|r1t|nddd	}g }|dkrt d
 t	|D ]}t d|d  d t 
d\}}}	|t|k rd|| ni }
| t jd| |
ddd| ddd}W d   n1 sw   Y  |+ t jddg| |
dd|v r||
ddd ndd| dd}W d   n1 sw   Y  |	 t jd|
ddd| dd d}W d   n1 sw   Y  |r|r|r||||d! t d
 qEt jd"d#d$}|rk|dkrt||krt d% 	 W d   dS | ||\}}|rct d&|  |rYt dt| d' |D ]}t d(|d  d)|d  d*|d   q@nt d+ t   nt d,|  W d   n	1 svw   Y  |rt d- t|dD ]\}}t | d.|d  d)|d  d*|d   qdS t d/ dS )0z
    Render foreign key relationship editor.
    
    Args:
        settings_service: Settings service instance
        collection_name: Name of the collection
    z
    Define foreign key relationships to validate data integrity.
    The system will check if referenced values exist in target collections.
    foreign_keys_z**Configure Foreign Keys**zXAdd relationships where fields in this collection reference fields in other collections.zNumber of Foreign Keysr   
   z/How many foreign key relationships to configure)r/   r0   r'   r)   r   z**Foreign Key #r3   z**   z	Field in field 	fk_field_zDField name in this collection (e.g., athlete_code, competition_code)athlete_code)r'   rH   r)   r*   NzReferences Collectionreferences_collectionfk_ref_coll_zTarget collection name)optionsro   rH   r)   zReferences Fieldreferences_fieldfk_ref_field_z0Field name in target collection (e.g., code, id)code)r   r   r   u   💾 Save Foreign Keysr6   r5   uN   ❌ Please fill in all foreign key fields or reduce the number of foreign keysu'   ✅ Foreign keys saved for collection: z foreign key(s) configured:**ry   r   .z4Foreign key validation disabled for this collection.u!   ❌ Failed to save foreign keys: z**Current Foreign Keys:**z. uI   ℹ️ No foreign keys configured. Data integrity validation is disabled.)r   r	   get_foreign_keysr]   r\   r^   r8   r:   rX   ranger   r9   r{   r_   ro   appendr;   r   update_foreign_keysr   r   r!   rR   	enumerate)r   rd   current_fksall_collectionsnum_fksforeign_keysir"   r#   r@   
current_fkr   ref_collection	ref_fieldr   r   r   fkidxr   r   r   r   e  s   





	(	
	
K,

Z
0r   )__doc__	streamlitr   services.settings_servicer   services.mongor   r   dictr   r   r   intr<   r?   rK   r    r   r`   r   r   r   r   r   r   <module>   sd    *
s
"
3
B  =