import pylab as plt
import numpy as np
from astrometry.util.fits import *
from astrometry.libkd.spherematch import match_radec
import fitsio
import os
from collections import Counter
from scipy.ndimage.measurements import label, find_objects
import time

#import sys
#sys.path.append('legacypipe/py')

from legacypipe.survey import LegacySurveyData
from tractor import PointSource, RaDecPos, NanoMaggies, Tractor
import matplotlib.cm

import warnings
warnings.simplefilter("ignore")


def try_one_ccd(X):
    try:
        return one_ccd(X)
    except:
        print('try_one_ccd:', X)
        import traceback
        traceback.print_exc()
    (_,_,i,_) = X
    return i,None

def one_ccd(X):
    (survey, ccd, iccd, nccds) = X
    imgfn = ccd.image_filename.strip()
    #outfn = os.path.join('cosmo/data/legacysurvey/dr9/south/outlier-masks', imgfn).replace('.fits.fz', '-outlier.fits.fz')
    outfn = os.path.join(survey.survey_dir, 'outlier-masks', imgfn).replace('.fits.fz', '-outlier.fits.fz')
    if not os.path.exists(outfn):
        print('Missing:', outfn)
        return iccd,None
    #imgfn = os.path.join('cosmo/staging', imgfn)

    results = fits_table()
    results.image_filename = []
    results.image_hdu = []
    results.ccdname = []
    results.expnum = []
    results.filter = []
    results.mjd_obs = []
    results.npix = []
    results.ra = []
    results.dec = []
    results.chisqperpix = []
    results.fluxsn = []
    results.flux = []
    results.flux_err = []
    results.fracin = []

    #img = fitsio.read(imgfn, ext=ccd.ccdname)
    mask = fitsio.read(outfn, ext=ccd.ccdname)
    L,n = label(mask == 1)
    slcs = find_objects(L)
    im = survey.get_image_object(ccd)
    #wcs = im.get_wcs()

    #print('CCD', imgfn, 'ext', ccd.ccdname)
    print('CCD %i of %i:' % (iccd+1, nccds), im, ':', len(slcs), 'blobs of outlier pixels')