U
    h8                     @   s   d Z ddlZddlmZ ddlmZ ddlmZ ddlm	Z	m
Z
mZ G dd dejZG d	d
 d
ejZG dd dejZG dd dejZdS )z
Django Forms for Streams Application

This module contains form definitions for creating and editing
streaming channels, configurations, and related models.
    N)forms)URLValidatorslugify)ChannelVideoConfigurationAudioConfigurationc                       sX   e Zd ZdZG dd dZ fddZ fddZd fd	d
	Zdd Zdd Z	  Z
S )ChannelFormz
    Form for creating and editing streaming channels.
    
    Provides validation for channel configuration including
    URL validation, slug generation, and configuration defaults.
    c                   @   s   e Zd ZeZddddddddd	g	Zejd
dddejd
dddej	d
dddde
 ejd
ddddejd
ddddejd
ddddejd
dddddZdddddddZd S )!zChannelForm.Metanamehls_urldescription	is_activeoutput_directorysegment_durationmax_segmentsretry_attemptsretry_intervalfmt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500zEnter channel nameclassplaceholderattrszhttps://example.com/stream.m3u8   z#Optional description of the channel)r   rowsr      <   r   minmaxd      i,  )r
   r   r   r   r   r   r   r   z#Human-readable name for the channelz"HTTP Live Streaming URL to capturez.Duration of each HLS segment in seconds (1-60)z*Maximum number of segments to keep (1-100)z*Number of retry attempts on failure (1-20)z&Seconds between retry attempts (1-300))r
   r   r   r   r   r   N)__name__
__module____qualname__r   modelfieldsr   	TextInputURLInputTextareaHiddenInputNumberInputwidgets
help_texts r.   r.   7/var/www/html/StreamProcessor/src/apps/streams/forms.pyMeta   sj         &r0   c                    s$   t  j|| | jjs d| jd< dS )z7Initialize form with default values and custom styling.z/app/media/streams/tempr   N)super__init__instancepkinitial)selfargskwargs	__class__r.   r/   r2   M   s    zChannelForm.__init__c                    s   t   }|d}|rt| }tdd|}tdd|}|d}|rd|d  rdd| }t	|dk rd|pxd	 d
d }|}d}t
jj|d}| jjr|j| jjd}| sq| d| }|d7 }q||d< d| |d< |S )zV
        Generate slug and output directory from name during form validation.
        r
   z
[^a-z0-9-] z-+-r   zchannel-r   newN2   r   )slug)r4   r?   /app/media/streams/r   )r1   cleangetr   lowerresubstripisdigitlenr   objectsfilterr3   r4   excludeexists)r6   cleaned_datar
   Z	base_slugr?   counterexistingr9   r.   r/   rA   V   s.    




zChannelForm.cleanTc                    sT   t  jdd}t| drDd| jkr.| jd |_d| jkrD| jd |_|rP|  |S )zQ
        Save the channel with auto-generated slug and output directory.
        F)commitrM   r?   r   )r1   savehasattrrM   r?   r   )r6   rP   channelr9   r.   r/   rQ      s    


zChannelForm.savec                 C   sD   | j d}|r.ddlm} ||}d| S ddlm} |jd S )z
        Auto-generate output directory based on channel name.
        
        Returns:
            str: Generated output directory path
        r
   r   r   r@   )settings
OUTPUT_DIR)rM   rB   django.utils.textr   django.confrT   STREAM_CONFIG)r6   r
   r   channel_slugrT   r.   r.   r/   clean_output_directory   s    
z"ChannelForm.clean_output_directoryc                 C   s>   | j d}|s|S t }|| | ds:td|S )z
        Validate HLS URL format and accessibility.
        
        Returns:
            str: Validated HLS URL
            
        Raises:
            ValidationError: If URL is invalid or inaccessible
        r   z.m3u8zHLS URL should end with .m3u8)rM   rB   r   rC   endswithr   ValidationError)r6   url	validatorr.   r.   r/   clean_hls_url   s    

zChannelForm.clean_hls_url)T)r"   r#   r$   __doc__r0   r2   rA   rQ   rZ   r_   __classcell__r.   r.   r9   r/   r	      s   6	-r	   c                   @   s&   e Zd ZdZG dd dZdd ZdS )VideoConfigurationFormzF
    Form for creating and editing video encoding configurations.
    c                   @   s   e Zd ZeZddddddddd	d
g
Zejddddejddddejddddejdddddejddddejddddej	ddidej	ddidej	ddidejddddd
Z
dS )zVideoConfigurationForm.Metar
   
resolutionaspect_ratio
frame_ratemin_bitratemax_bitratecodecpresetprofilelevelr   Configuration namer   r   Z	1920x1080z16:9r   x   r   2000k4000kr   z3.1)
r
   rc   rd   re   rf   rg   rh   ri   rj   rk   N)r"   r#   r$   r   r%   r&   r   r'   r+   Selectr,   r.   r.   r.   r/   r0      sl             r0   c                 C   s   | j d}|r|d}t|dkr0tdz2t|d t|d  }}|dks\|dkr`tW n tk
r   tdY nX |S )z
        Validate resolution format (WIDTHxHEIGHT).
        
        Returns:
            str: Validated resolution
            
        Raises:
            ValidationError: If resolution format is invalid
        rc   x   z;Resolution must be in format WIDTHxHEIGHT (e.g., 1920x1080)r   r   z/Resolution dimensions must be positive integers)rM   rB   splitrH   r   r\   int
ValueError)r6   rc   partswidthheightr.   r.   r/   clean_resolution   s    


z'VideoConfigurationForm.clean_resolutionN)r"   r#   r$   r`   r0   ry   r.   r.   r.   r/   rb      s   1rb   c                   @   s&   e Zd ZdZG dd dZdd ZdS )AudioConfigurationFormzF
    Form for creating and editing audio encoding configurations.
    c                   @   s~   e Zd ZeZddddddgZejddd	d
ejddid
ejddd	d
ejddid
ejddid
ej	ddid
dZ
dS )zAudioConfigurationForm.Metar
   rh   bitratesample_ratechannels	normalizer   rl   r   r   r   128kzGfocus:ring-primary-500 h-4 w-4 text-primary-600 border-gray-300 rounded)r
   rh   r{   r|   r}   r~   N)r"   r#   r$   r   r%   r&   r   r'   rp   CheckboxInputr,   r.   r.   r.   r/   r0     sB           r0   c                 C   sl   | j d}|rh| ds(tdz t|dd }|dkrFtW n tk
rf   tdY nX |S )z
        Validate audio bitrate format.
        
        Returns:
            str: Validated bitrate
            
        Raises:
            ValidationError: If bitrate format is invalid
        r{   kz&Bitrate must end with "k" (e.g., 128k)Nr   z1Bitrate must be a positive number followed by "k")rM   rB   rC   r[   r   r\   rt   ru   )r6   r{   rater.   r.   r/   clean_bitrate6  s    

z$AudioConfigurationForm.clean_bitrateN)r"   r#   r$   r`   r0   r   r.   r.   r.   r/   rz     s   rz   c                   @   sX   e Zd ZdZejej ddej	ddiddZ
ejej ddej	ddiddZd	S )
StreamStartFormzK
    Form for starting a stream with optional configuration selection.
    FzUse default video settingsr   r   r   )querysetrequiredempty_labelwidgetzUse default audio settingsN)r"   r#   r$   r`   r   ModelChoiceFieldr   rI   allrp   video_configr   audio_configr.   r.   r.   r/   r   Q  s&    	 r   )r`   rD   djangor   django.core.validatorsr   rV   r   Zapps.streams.modelsr   r   r   	ModelFormr	   rb   rz   Formr   r.   r.   r.   r/   <module>   s    4Q>