from mhelper import file_helper
from pyguisignal.__main__ import config
from pyguisignal import general


def process_resource( designer_filename: str, init_filename: str, logic_filename: str ):
    """
    Processes the resource "qrc" file
    
    :param designer_filename:       .QRC file (in) 
    :param init_filename:           Compile _RC.PY file (out) 
    :param logic_filename:          Created .PY logic file (out) 
    :return: 
    """
    print( "PROCESS RESOURCE: " + file_helper.get_filename( designer_filename ) )
    
    if config.verbose:
        print( "---- DESIGNER FILE            : " + designer_filename )
        print( "---- INITIALISATION FILE      : " + init_filename )
        print( "---- LOGIC FILE               : " + logic_filename )
    
    #
    # Create logic file
    #
    content = file_helper.read_all_lines( designer_filename )
    
    result = []
    result.append( '"""Resources names. File automatically generated by PyGuiSignal. Modifications may be overwritten."""' )
    result.append( "from mhelper import ResourceIcon" )
    
    spec_prefix = None
    
    for line in content:
        line = line.strip()
        
        if line.startswith( '<qresource prefix="' ) and line.endswith( '">' ):
            spec_prefix = line[19:-2]
            
            break
    
    if spec_prefix is None:
        print( "Resource file must specify prefix." )
        spec_prefix = input( "PREFIX=" )
    
    prefix = ":/" + spec_prefix + "/"
    
    r = []
    r.append( "<RCC>" )
    r.append( '    <qresource prefix="{}">'.format( spec_prefix ) )
    
    for file in file_helper.list_dir( file_helper.get_directory( designer_filename ) ):
        filename = file_helper.get_file_name( file )
        if filename.startswith( "." ):
            continue
        
        if not file_helper.get_extension( filename ).lower() in (".svg", ".png", ".jpg"):
            continue
        
        name = file_helper.get_filename_without_extension( file )
        name = name.replace( "-", "_" )
        r.append( "        <file>" + filename + "</file>" )
        result.append( '{} = ResourceIcon( "{}{}" )'.format( name, prefix, filename ) )
    
    r.append( "    </qresource>" )
    r.append( "</RCC>" )
    
    rs = "\n".join( r )
    
    if rs != content:
        file_helper.write_all_text( designer_filename, rs )
        
    file_helper.write_all_text( logic_filename, "\n".join( result ) )
    
    #
    # QRC --> _RC.PY
    #
    command = config.resource_command.format( designer_filename, init_filename )
    general.run_system( command )
