import os
import logging

class ChipOutput(object):
    def __init__(self, config, focal_plane, chip, filt, imgKey0="", imgKey1="", imgKey2="", exptime=150., mjdTime="", ra_cen=None, dec_cen=None, pointing_type='MS', pointing_ID='0', subdir="./", prefix=""):
        self.focal_plane = focal_plane
        self.chip = chip
        self.filt = filt
        self.imgKey0 = imgKey0
        self.imgKey1 = imgKey1
        self.imgKey2 = imgKey2
        self.exptime = exptime
        self.mjdTime = mjdTime
        self.pointing_type = pointing_type
        if (ra_cen is not None) and (dec_cen is not None):
            self.ra_cen = ra_cen
            self.dec_cen = dec_cen
        else:
            self.ra_cen = config["obs_setting"]["ra_center"]
            self.dec_cen = config["obs_setting"]["dec_center"]
        exp_name = imgKey0 + "_%s_%s.fits"
        self.chipLabel = focal_plane.getChipLabel(chip.chipID)
        self.img_name =  prefix + exp_name%(self.chipLabel, filt.filter_type)
        
        # self.cat_name = 'MSC_' +  config["obs_setting"]["date_obs"] + config["obs_setting"]["time_obs"] + "_" + str(pointing_ID).rjust(7, '0') + "_" + self.chipLabel.rjust(2,'0') + ".cat"

        self.cat_name = "MSC_1%s_chip_%s_filt_%s"%(str(pointing_ID).rjust(8, '0'), focal_plane.getChipLabel(chip.chipID), filt.filter_type) + ".cat"

        self.subdir = subdir

        # Setup logger for each chip
        logger_filename = "MSC_1%s_chip_%s_filt_%s"%(str(pointing_ID).rjust(8, '0'), focal_plane.getChipLabel(chip.chipID), filt.filter_type) + ".log"
        self.logger = logging.getLogger()
        fh = logging.FileHandler(os.path.join(self.subdir, logger_filename), mode='w+', encoding='utf-8')
        fh.setLevel(logging.DEBUG)
        self.logger.setLevel(logging.DEBUG)
        logging.getLogger('numba').setLevel(logging.WARNING)
        # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        formatter = logging.Formatter('%(asctime)s - %(msecs)d - %(levelname)-8s - [%(filename)s:%(lineno)d] - %(message)s')
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)

        hdr1  = "# obj_ID ID_chip filter xImage yImage ra dec ra_orig dec_orig z mag obj_type "
        hdr2  = "thetaR bfrac hlr_disk hlr_bulge e1_disk e2_disk e1_bulge e2_bulge g1 g2 "
        hdr3  = "sed_type av redden "
        hdr4 = "pm_ra pm_dec RV parallax"

        fmt1  = "%10d %4d %5s %10.3f %10.3f %15.8f %15.8f %15.8f %15.8f %7.4f %8.4f %15s "
        fmt2  = "%8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f "
        fmt3 = "%2d %8.4f %8.4f "
        fmt4 = "%15.8f %15.8f %15.8f %15.8f"

        self.hdr = hdr1 + hdr2 + hdr3 + hdr4
        self.fmt = fmt1 + fmt2 + fmt3 + fmt4

        self.logger.info("pointing_type = %s\n"%(pointing_type))


    def update_ouptut_header(self, additional_column_names=""):
        self.hdr += additional_column_names

    def create_output_file(self):
        if self.pointing_type == 'MS':
            self.cat = open(os.path.join(self.subdir, self.cat_name), "w")
            self.logger.info("Creating catalog file %s ...\n"%(os.path.join(self.subdir, self.cat_name)))
            if not self.hdr.endswith("\n"):
                self.hdr += "\n"
            self.cat.write(self.hdr)

    def cat_add_obj(self, obj, pos_img, pos_shear):
        ximg = pos_img.x - self.chip.bound.xmin + 1.0
        yimg = pos_img.y - self.chip.bound.ymin + 1.0
        
        line = self.fmt%(
            obj.id, int(self.chipLabel), self.filt.filter_type, ximg, yimg, obj.ra, obj.dec, obj.ra_orig, obj.dec_orig, obj.z, obj.getMagFilter(self.filt), obj.type, 
            obj.thetaR, obj.bfrac, obj.hlr_disk, obj.hlr_bulge, obj.e1_disk, obj.e2_disk, obj.e1_bulge, obj.e2_bulge, obj.g1, obj.g2,
            obj.sed_type, obj.av, obj.redden,
            obj.pmra, obj.pmdec, obj.rv, obj.parallax)
        line += obj.additional_output_str
        if not line.endswith("\n"):
            line += "\n"
        self.cat.write(line)
