import os
import subprocess
import joblib
from subprocess import Popen

# try:
#     import importlib.resources as pkg_resources
# except ImportError:
#     # Try backported to PY<37 'importlib_resources'
#     import importlib_resources as pkg_resources

class Detection(object):
    def __init__(self, n_jobs=4, output_dir=None):
        self.CONFIG_PATH = os.path.join(os.path.dirname(__file__), "data/")
        self.n_jobs = n_jobs
        if output_dir:
            self.output_dir = output_dir
        else:
            self.output_dir = os.path.dirname(__file__)
    
    def run_sextractor(self, image, weight, flag, psf=None, sex_config=None, sex_param=None, output_cat=None):
        if output_cat is None:
            basename = os.path.basename(image)
            output_cat = basename.replace(".fits", "_extracted.cat")
            output_cat = os.path.join(self.output_dir, output_cat)
        
        if sex_config is None:
            sex_config = os.path.join(self.CONFIG_PATH, "default.config")
        if sex_param is None:
            sex_param = os.path.join(self.CONFIG_PATH, "default.param")
        filter_path = os.path.join(self.CONFIG_PATH, "default.conv")
        nnw_path = os.path.join(self.CONFIG_PATH, "default.nnw")
        
        sex_cmd1 = 'sex ' + image + ', ' + image
        sex_cmd2 = ' -c ' + sex_config
        sex_cmd3 = ' -CATALOG_NAME ' + output_cat + ' -WEIGHT_IMAGE ' + weight \
                      + ' -FLAG_IMAGE ' + flag
        sex_cmd4 = ' -PARAMETERS_NAME ' + sex_param + ' -FILTER_NAME ' + filter_path \
                      + ' -STARNNW_NAME ' + nnw_path
        sex_cmd5 = ''
        if psf is not None:
            sex_cmd5 += ' -PSF_NAME ' + psf
        sex_cmd = sex_cmd1 + sex_cmd2 + sex_cmd3 + sex_cmd4 + sex_cmd5
        print(sex_cmd)
        p = Popen(sex_cmd, shell=True)
        p.wait()

    def run_detection(self, image_list, weight_list, flag_list, psf_list=None, sex_config=None, sex_param=None, output_cat_list=None):
        assert len(image_list) == len(weight_list), "length of image list must be equal to length of weight list"
        assert len(image_list) == len(flag_list), "length of image list must be equal to length of flag list"
        if psf_list:
            assert len(image_list) == len(psf_list), "length of image list must be equal to length of psf list"
        else:
            psf_list = [None for i in range(len(image_list))]
        if output_cat_list:
            assert len(image_list) == len(output_cat_list), "length of image list must be equal to length of output catalog path list"
        else:
            output_cat_list = [None for i in range(len(image_list))]
        
        joblib.Parallel(n_jobs=self.n_jobs)(joblib.delayed(self.run_sextractor)(image=image_list[i], weight=weight_list[i], flag=flag_list[i], psf=psf_list[i], sex_config=sex_config, sex_param=sex_param, output_cat=output_cat_list[i]) for i in range(len(image_list)))
            
        