import os
import glob
from ..utils.utils import run_command, create_symlink

# indir = psbas, ifall = intfdir
def velkml(indir, ifall, paths):
    print(f'Converting vel grd to kml for {os.path.basename(indir)}')
    os.chdir(indir)
    IFGs = next(os.walk(ifall))[1]
    for key in ["pF1", "pF2", "pF3"]:
        dir_path = paths.get(key)
        if dir_path and os.path.exists(dir_path):
            intfdir = os.path.join(dir_path, "intf_all")                               
            break
    # The gauss_* file is processed only in subswath IFGs. 
    # That's why we need to check if 'ifall' refers to merged IFGs if they exist, 
    # and use 'intfdir' for any subswath IFG.
    g = os.path.join(intfdir, IFGs[0], 'gauss_*')

    # link requried files
    create_symlink(os.path.join(ifall, 'trans.dat'), '.')   
    run_command(f'ln -s {g} .')
    

    if not os.path.exists('vel_ll.grd'):
        # Convert vel.grd to geographic coordinates using proj_ra2ll.csh
        run_command("proj_ra2ll.csh trans.dat vel.grd vel_ll.grd")

        # Generate a color palette table (CPT) for the grid
        run_command("gmt grd2cpt vel_ll.grd -T= -Z -Cjet > vel_ll.cpt")


        # Generate the KML file from the .grd file
        run_command("grd2kml.csh vel_ll vel_ll.cpt")
        '''gmt grd2cpt: This is a command from the Generic Mapping Tools (GMT) suite that generates a color palette table (CPT) based on the data in a grid file.
    vel_ll.grd: The input grid file containing your raster data (e.g., velocity values).
    -T=: Specifies that the CPT should be scaled automatically to cover the range of the grid. The = means GMT will choose limits based on the data's actual min/max values.
    -Z: Ensures that the CPT is continuous, without discrete color bands. This produces a gradient effect across the color scale.
    -Cjet: Specifies the color scheme to use, in this case, jet, which is a popular color scale that transitions through blue, cyan, green, yellow, and red.
    > vel_ll.cpt: Redirects the output to a file named vel_ll.cpt, which stores the generated CPT.'''

        # Add a legend to the KML file
        run_command(
            "gmt psscale -Cvel_ll.cpt -Dx1i/0.5i+w5i/0.25i -Bx5f5+l\"Velocity (mm/yr)\" -By+f\"%.2f\" > legend.ps")
        '''gmt psscale: This command creates a color scale (legend) based on a given CPT file.
    -Cvel_ll.cpt: Specifies the CPT file to use (vel_ll.cpt), which was generated by grd2cpt.
    -Dx1i/0.5i+w5i/0.25i: Sets the position and size of the scale bar.
        -D indicates that a scale bar is to be drawn.
        x1i/0.5i sets the reference point of the scale (1 inch from the left and 0.5 inches from the bottom).
        w5i/0.25i specifies the width (5 inches) and height (0.25 inches) of the scale bar.
    -Bx5f5+l"Velocity (mm/yr)":
        -Bx5f5 specifies the annotations on the x-axis. The 5 means major ticks are labeled every 5 units, and f5 adds minor ticks every 5 units.
        +l"Velocity (mm/yr)" adds a label to the x-axis.
    -By+f"%.2f": Formats the numbers on the scale to show only two decimal places (%.2f).
    > legend.ps: Redirects the output to a PostScript file named legend.ps, which contains the visual representation of the legend.'''

        run_command("gmt psconvert legend.ps -A -Tg -W+k+l100/100 > legend.png")
        '''gmt psconvert: This is a GMT command used to convert PostScript (PS) files to other formats, such as PNG, PDF, or JPG.
legend.ps: The input file in PostScript format that you want to convert (in this case, the legend generated by the psscale command).
-A: Trims the output by removing any surrounding white space around the content. This makes the output image more compact and eliminates unnecessary margins.
-Tg: Specifies the output format, with g indicating PNG format (e.g., -Tg means the output will be legend.png).
-W+k+l100/100:

    -W: Applies anti-aliasing to improve the appearance of the image.
    +k: Ensures that the background color is kept in the output.
    +l100/100: Controls the DPI (dots per inch) for the output image, where 100/100 sets the horizontal and vertical DPI to 100. This affects the resolution and quality of the resulting image.'''

        # Assuming the KML file was named `vel_ll.kml`:
        with open('vel_ll.kml', 'r') as file:
            kml_data = file.read()

        legend_overlay = """
		<ScreenOverlay>
			<name>Legend</name>
			<Icon>
				<href>legend.png</href>
			</Icon>
			<overlayXY x="0" y="0" xunits="fraction" yunits="fraction"/>
			<screenXY x="0.05" y="0.05" xunits="fraction" yunits="fraction"/>
			<rotationXY x="0" y="0" xunits="fraction" yunits="fraction"/>
			<size x="0.05" y="0.5" xunits="fraction" yunits="fraction"/>
		</ScreenOverlay>
		"""

        # Insert the legend inside the <Document> tag
        if '<Document>' in kml_data:
            kml_data = kml_data.replace('<Document>', '<Document>' + legend_overlay)
        else:
            print("Error: No <Document> or <Folder> tag found in KML file.")

        # Insert the legend overlay before the closing tag
        # kml_data = kml_data.replace("</kml>", legend_overlay)

        # Write the updated KML data back to the file
        with open('vel_ll_with_legend.kml', 'w') as file:
            file.write(kml_data)

        print('Created KML file')


def projgrd(indir):
    print(f'Projecting for {indir}')
    os.chdir(indir)
    grds = glob.glob(indir + '/disp*.grd')
    grdsout = [x.replace('.grd', '_ll.grd') for x in grds]
    for i in range(0, len(grds)):
        print(f'{i} Projecting {os.path.basename(grds[i])}')
        run_command(f'proj_ra2ll.csh trans.dat {grds[i]} {grdsout[i]}')