import math  # mathematical functions
import subprocess  # calling to the terminal
from astropy.io import fits  # Open and Reading FITS Files usign astropy
import random  # pseudo-random generator
import seaborn as sns  # Improvements for statistical-plots
from WL_Utils import sex_caller
from Class_CrossMatching import CrossMatching
from Class_CatalogReader import CatalogReader


# Get first catalogs
# sex_caller('lhn1n1_2010apr_r_stack_fc_fix.fits', 'lhn1n1_2010apr_r_stack_fc_fix')
# sex_caller('lhn1n1_2010dec_z_stack_fc_fix.fits', 'lhn1n1_2010dec_z_stack_fc_fix')

# Read catalogs
catag_r = CatalogReader("lhn1n1_2010apr_r_stack_fc_fix.cat")
catag_r.read()

catag_z = CatalogReader("lhn1n1_2010dec_z_stack_fc_fix.cat")
catag_z.read()

# Give value to the cross-matching radius

r = 3

# Create object for cross-matching
crossmatching = CrossMatching(catag_r.fcat, catag_z.fcat)
crossmatching.kdtree(n=r * 1e-06)
crossmatching.catalog_writter("lhn1n1_crossmatching_1to2", compare="1to2")
print "\n"
crossmatching.catalog_writter("lhn1n1_crossmatching_2to1", compare="2to1")
mag_output_wayback = []
mag_output_error_sex = []
mag_output_error_wayback = []
flux_input = []
flux_output = []
flux_output_error = []
flux_output_max = []
flux_output_max_error = []
number_lost_objects = []

# Call Source Extractor

catalog_name = sex_caller("{}.fits".format(PICTURE), "{}_{}".format(PICTURE, FILTER))

# Read catalog
catag = CatalogReader(catalog_name)
catag.read()

# Create object for simulation
simulation = ObjectCreator(catag.fcat)
simulation.general_histograms(catag.fcat)
print "\nMasking . . . {}\n"


# For-loop for 1 to 30 mag
for mag in mag_input:
    simulation.matrix_data = []
    simulation.masking_matrix("{}.fits".format(PICTURE))
    print "\nRound {}\n".format(mag)
    simulation.packing_percentage(number_objects=4000)
    simulation.out_mag = []