# -*- coding: utf-8 -*-
"""
Created on Tue Sep 24 16:36:14 2024

@author: masanobu-new
"""

# -*- coding: utf-8 -*-
"""
Created on Tue Sep 24 16:36:14 2024

@author: masanobu-new
"""

import os
import sys
from pathlib import Path
import hozenLib
from pathlib import Path
# グローバル変数を定義
global_vars = {}
 
    

def process_image(image_path, inclination, lowH, highH, lowV, highV, tmp_path):
    for n in range(1, 5):
        print(f"Processing image {n}...")
        clip_image_path = tmp_path / f"{image_path.stem}_{n}.jpg"  # This should work now

        # Extract vegetation and soil pixels
        try:
            binVeg, binSoil = hozenLib.getVegAndSoil(str(clip_image_path), lowH, highH, lowV, highV)

            # Generate save paths
            green_path = clip_image_path.with_name(f"{clip_image_path.stem}_veg.jpg")
            print ('pass: ',green_path)
            soil_path = clip_image_path.with_name(f"{clip_image_path.stem}_soil.jpg")

            # Save images
            hozenLib.imwrite(str(green_path), binVeg)
            hozenLib.imwrite(str(soil_path), binSoil)

            print(f"Saved vegetation image to {green_path}")
            print(f"Saved soil image to {soil_path}")
             
        except Exception as e:
            print(f"Error processing image {clip_image_path}: {e}")
            
         

if __name__ == "__main__":
    
    args = sys.argv
    #args = ['clip.py', 'C:/Users/user/Desktop/Temp/GS__0645.JPG', -55, 70, 150, 0, 80]

try:
    # Set up image path and temporary folder
    image_path = Path(args[1])
    sub_folder = 'tmpfiles'
    base_folder_path = image_path.parent
    tmp_path = base_folder_path / sub_folder

    # Create the temporary folder
    tmp_path.mkdir(parents=True, exist_ok=True)

    # Extract parameters from arguments
    inclination, lowH, highH, lowV, highV = map(int, args[2:7])
    
    # Convert image format
    hozenLib.conv_e2p(str(image_path), float(inclination), str(tmp_path))

    # Process images
    process_image(image_path, inclination, lowH, highH, lowV, highV, tmp_path)

except Exception as e:
    print(f"エラーが発生しました: {e}")