
    ג[ic                         d Z ddlZddlmZ ddlmZ dedefdZdedefd	Z	dededefd
Z
dededededef
dZdededefdZdedededededefdZdedefdZdedefdZdedefdZdefdZdedef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                 f   t          j        d           t          j        d           t          j        d           t          j        d           |                                 }t          ||           t          j        d           t          | ||           t          j        d           t          j        d           t          j        d           t          | |           t          j        d           t          j        d           t          j        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_settingss      ,/var/www/html/IGF-ODF-V3/ui/tabs/settings.pyrender_settings_tabr      s"    HKHIIIK I0111 (<<>> m-=>>>K /@PQQQKK I-...$%5}EEEKK I,---!"233333    r   c                 0   t          j        d           t          j        d          \  }}|5  |                                 rt          j        d           nAt          j        d           |                                 }|rt          j        d|            ddd           n# 1 swxY w Y   |5  t          j        d|d          d	           ddd           n# 1 swxY w Y   |d
         }t          |          }t          j	        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_uris          r   r   r   <   s    L1222AJD$	 0 0%%'' 	0J23333H4555!6688E 0.u..///0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
 J J
H)9*)EHHHIIIJ J J J J J J J J J J J J J J 5
!C3JG+z++,,,,,s$   A+B%%B),B)2CC!$C!c           
         t          j        d           t          j        d           t          j        d          5  t          j        d           t          j        d|d         r|d         nddd	d
          }t          j        d|d         dd          }t          j        d           t          j        d          \  }}|5  t          j        ddd|d         dd          }ddd           n# 1 swxY w Y   |5  t          j        ddd|d         dd          }ddd           n# 1 swxY w Y   t          j        d           t          j        g d          \  }}}	|5  t          j        dd           }
ddd           n# 1 swxY w Y   |5  t          j        d!d"           }ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   |
rt          | ||||           |r)||||d#t           j	        _
        t          j                     d$t           j	        v r"t          | |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   )   r7   r   u   🧪 Test Connection	secondaryr,   u   💾 Save Settingsprimary)r   r   r1   r6   pending_settings)r	   r   r   form
text_inputr   number_inputform_submit_button_handle_test_connectionsession_stater;   rerun_show_save_confirmation)r   r   r   r   r   r%   r&   r1   r6   col3test_buttonsave_buttons               r   r   r   Z   s    L%&&&K  	 	 	 
(	)	) ; ;
,--- m-=e-D  }"5))  K}X K
 
 
 =":.6"	
 
 
 	9:::Z]]
d 	 	!#$&';<:" " "	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  	 	')*&'AB8( ( ($	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	E :iii00dD 	 	/&   K	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  	 	/$  K	 	 	 	 	 	 	 	 	 	 	 	 	 	 	o; ; ; ; ; ; ; ; ; ; ; ; ; ; ;|  
$	
 	
 	
    "4(@	-
 -
) 	


 R-- 
-	
 	
 	
 	
 	

 
s   B	G!C3'G3C7	7G:C7	;G !D-!G-D1	1G4D1	53G(F?GF	GF	GF;/G;F?	?GF?	GGGr   r   r1   r6   c                 r   t          j        d          5  |                     ||||          \  }}ddd           n# 1 swxY w Y   |r.t          j        d           t          j        d| d           dS t          j        d           t          j        d|            t          j        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   r1   r6   r   r    s          r   r@   r@      s   " 
+	,	, 
 
)99$	
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
  K

8999
CCCCDDDDD
2333
&u&&'''

IJJJJJs   =AAr;   c           
         t          j        d           t          j        d           t          j        d|d          d|d          d|d          d	           t          j        d
          \  }}|5  t          j        dddd          r8t          | ||d         |d         |d         |d                    t           j        `ddd           n# 1 swxY w Y   |5  t          j        ddd          r3t           j        `t          j        d           t          j	                     ddd           dS # 1 swxY 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:** r1   z'ms
    - **Server Selection Timeout:** r6   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 Savestretchr:   confirm_save_btn)widthr,   keyr   Nu
   ❌ Cancelcancel_save_btn)rN   rO   z%Save cancelled. No changes were made.)
r	   r   rJ   r   button_execute_saverA   r;   r"   rB   )r   r   r;   r%   r&   s        r   rC   rC      s    KJ3444K 
&z2
 
  00DE
 
 &66P%Q	
 
 
 
	 
	 
	 AJD$	 2 29'yyN`aaa 
	2  ' , !56 !;<    12 2 2 2 2 2 2 2 2 2 2 2 2 2 2 
  9\8IJJJ 	 1G;<<<HJJJ                 s&   2ACCCAD44D8;D8c                    t          j        d          5  |                     ||||          \  }}ddd           n# 1 swxY w Y   |rmt          j        d           t          j        d           |                                  t          j        d           t          j        ddd	          rt          j        d
          5  |                    d          |_	        |
                                }ddd           n# 1 swxY w Y   |rPt          j        d           t          j        d           t          j                     t          j                     dS t          j        d           |                                }|rt          j        d|            t          j        d           dS dS t          j        d           t          j        d|            t          j        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 Nowr:   reconnect_btn)r,   rO   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	   rH   save_mongodb_settingsr   r"   reload_configrJ   rQ   _load_configconfigconnectballoonsrB   r    r!   )	r   r   r   r   r1   r6   r   r    reconnect_successs	            r   rR   rR   "  s   & 
(	)	) 
 
)??$	
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
  $A

9:::
?@@@ 	&&((( 	
  	 	 	 9)	OOO 	H899 < <'4'A'ABZ'['[$$1$9$9$;$;!< < < < < < < < < < < < < < <
 ! H
>???FGGG




7888%::<< 4H2522333
FGGGGG#	H 	H& 	3444
&u&&'''

?@@@@@s!   =AA/DD	Dreturnc                     | sdS d| v rf|                      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:r7   unknownz
//***:***@)splitlen)r   partsprotocol_part	host_parts       r   r#   r#   d  s        cz 		#37583CSat,,Q// #E

Q=E!HHI	669666 
r   c                    t          j        d           |                                 }|st          j        d           dS t	          |                                          }t          j        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_collections        r   r   r   }  s     K  	 	 	 #6688K 
7888 K,,..//,(<    I!"24GHHHHHI Ir   collection_namec                 d	   |                      |          }t          j        d|            t          j        d|           5  t          j        d           t          j        d           |                    dg           }t          j        dd                    |          dd	d
          }t          j        d           t          j        d           |                    dg           }t          j        dd                    |          ddd          }t          j        d           |                    dd          }t          j        dg dg d	                    |          d          }t          j
        d|                    dd          d          }	t          j        d           t          j        dd !          }
|
rOd" |                    d          D             }d# |                    d          D             }|s(|d$k    r"t          j        d%           	 d&d&d&           d&S |s&|d'v r"t          j        d(           	 d&d&d&           d&S |                     |||||	          \  }}|rt          j        d)|            t          j        d*d+                    |          z   d,z   d+                    |          z   d-z   |z   d.z   t#          |	          z   d/z              t          j                     nt          j        d0|            d&d&d&           n# 1 swxY w Y   t          j        d           t          j        d1           t          j        d2          \  }}|5  t          j        d3           |r|D ]}t          j        d4|            nt          j        d5           d&d&d&           n# 1 swxY w Y   |5  t          j        d6           |r|D ]}t          j        d4|            nt          j        d5           d&d&d&           n# 1 swxY w Y   t          j        d7| d8           t          j        d9|                    dd          rd:nd;            t          j        d           t          j        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)rw   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 Configurationr:   r9   c                 ^    g | ]*}|                                 |                                 +S  strip.0ks     r   
<listcomp>z-_render_collection_editor.<locals>.<listcomp>  s2    \\\1RSRYRYR[R[\QWWYY\\\r   c                 ^    g | ]*}|                                 |                                 +S r}   r~   r   s     r   r   z-_render_collection_editor.<locals>.<listcomp>  s2    bbbaXYX_X_XaXab		bbbr   ry   uG   ❌ Business keys are required unless using 'alternative_only' strategyN)rx   ry   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   r<   r   get	text_areajoinri   rz   checkboxr?   r`   r    update_collection_configr   r"   strrZ   r   r$   _render_foreign_key_editor)r   rn   rX   current_business_keysbusiness_keys_textcurrent_alternative_keysalternative_keys_textcurrent_strategyrv   r{   	submittedrq   ru   r   r    r%   r&   rO   s                     r   rj   rj     s    33ODDFL7o77888	7o77	8	8 ]G ]G
1222
\]]] !'

?B ? ?\))122F*
 
 
 	6777
  E  	F  	F  	F $*::.@"#E#E  "))455N=!
 !
 !
 	+,,, "::&9>JJLJJJPPPVVWghh		
 	
 	
 + **Y--4
 
 
 	E )0
 
 
	
  $	G\\0B0H0H0N0N\\\Mbb3H3N3Nt3T3Tbbb ! %6:L%L bcccC]G ]G ]G ]G ]G ]G ]G ]GF $ (9=k(k WXXXK]G ]G ]G ]G ]G ]G ]G ]GP .FF ! NGU  G
WoWWXXX %'+yy'?'?@C(( +/))4D*E*EFI)) ,=	=@	
 "%W.
1    EeEEFFF{]G ]G ]G ]G ]G ]G ]G ]G ]G ]G ]G ]G ]G ]G ]G@ KK+,,,AJD$	    
()))  	 , ( (''''( GJ                              
    
+,,,# 	 / ( (''''( GJ                              K>+;>>>???KXVZZ	4-H-H V		hXXYYY KK/000/AAAAAsF   G!L%2L%B?L%%L),L)1AOO	O	AP&&P*-P*c           	         t          j        d           |                                 }t          j        d|dd           t          j        d          5  t          j        d           t          j        ddd	|d
d          }t          j        d           t          j        d           t          j        dd          }|r||k    rt          j        d           nu|                     |          \  }}|rDt          j        d|dd|d           t          j        d           t          j	                     nt          j
        d|            ddd           dS # 1 swxY w 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 Loadrs   i r0   zENumber of records to load from MongoDB for comparison (100 - 100,000)r2   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 Limitr:   r9   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"   r<   r>   r?   update_record_limitr   rZ   r    )r   current_limit	new_limitr   r   r    s         r   r   r   (  s    K  	 	 	 %5577MGGMGGGGHHH	$	%	% 'L 'L
*+++O%X
 
 
	 	  	 	 	 	E)$
 
 
	
  	LM) 
L78888!1!E!Ei!P!P LJ_M___R[___```GcdddKMMMMHJ5JJKKKO'L 'L 'L 'L 'L 'L 'L 'L 'L 'L 'L 'L 'L 'L 'L 'L 'L 'Ls   C?E""E&)E&c                 z   t          j        d           |                     |          }t          |                                                                           }t          j        d|           5  t          j        d           t          j        d           t          j        ddd|rt          |          ndd	          }g }|dk    rt          j        d
           t          |          D ]}t          j        d|dz    d           t          j
        d          \  }}}	|t          |          k     r||         ni }
|5  t          j        d| |
                    dd          d| dd          }ddd           n# 1 swxY w Y   |5  t          j        ddg|z   |
                    dd          |v r,|                    |
                    dd                    dz   ndd| d          }ddd           n# 1 swxY w Y   |	5  t          j        d|
                    dd          d| dd           }ddd           n# 1 swxY w Y   |r|r|r|                    |||d!           t          j        d
           t          j        d"d#$          }|r|dk    r5t          |          |k    r"t          j        d%           	 ddd           dS |                     ||          \  }}|rt          j        d&|            |rZt          j        dt          |           d'           |D ]1}t          j        d(|d          d)|d          d*|d                     2nt          j        d+           t          j                     nt          j        d,|            ddd           n# 1 swxY w Y   |r]t          j        d-           t/          |d          D ]6\  }}t          j        | d.|d          d)|d          d*|d                     7dS t          j        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)r3   r4   r+   r-   r   z**Foreign Key #r7   z**   z	Field in field 	fk_field_zDField name in this collection (e.g., athlete_code, competition_code)athlete_code)r+   rO   r-   r.   NzReferences Collectionreferences_collectionfk_ref_coll_zTarget collection name)optionsrz   rO   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 Keysr:   r9   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:**r   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_keysrg   rf   rh   r<   r>   ra   ranger   r=   r   ri   rz   appendr?   r    update_foreign_keysr   r"   r$   rZ   	enumerate)r   rn   current_fksall_collectionsnum_fksforeign_keysir%   r&   rD   
current_fkr   ref_collection	ref_fieldr   r   r    fkidxs                      r   r   r   e  s    K  	 	 	 #33ODDK +??AAFFHHIIO	222	3	3 WF WF
0111
nooo /$&18#k"""qB
 
 
 Q; -	#K7^^ *# *#5ac555666#%:a== dD 013{3C3C/CK[^^
  M5O55(nnWb99+OOc$2  E                 %'\/!# 6hrhvhv  xO  QS  iT  iT  Xg  ig  no33JNNCZ\^4_4_``cddd  mn.1..5& & &N                  "*(nn-?DD/A//O$*! ! !I                ^ 	  ''!&1?,5) )    E"""" )$
 
 
	
  	F{ s<00G; ijjjQWF WF WF WF WF WF WF WFV .AA/S_``NGU 
F
V_VVWWW TGQ\!2!2QQQRRR* s s qG q q2>U;V q qY[\nYo q qrrrrs GRSSSDUDDEEEoWF WF WF WF WF WF WF WF WF WF WF WF WF WF WFt  ]
/000 a00 	h 	hGCGsffbkff3J0KffbQcNdffgggg	h 	h 	[\\\\\s   4CN=4F<N=FN=FN=A%H:N=H

N=H
N=1IN=IN=IA?N=$CN==OO)__doc__	streamlitr	   services.settings_servicer   services.mongor   r   dictr   r   r   intr@   rC   rR   r#   r   rj   r   r   r}   r   r   <module>r      sh  
 
     5 5 5 5 5 5 ' ' ' ' ' ''4/ '4, '4 '4 '4 '4T-\ -T - - - -<p
%p
p
 p
 p
 p
 p
fK%K	K K 	K
 "K K K KD0%00 0 0 0 0f?A%?A?A 
?A 	?A
 ?A "?A ?A ?A ?AD3 3    2I IWc I I I I@HB HBRU HB HB HB HBV:LO :L :L :L :Lzr] r]SV r] r] r] r] r] r]r   