# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
#     FORMATS = {'DEFAULT'       : "%(message)s",
#                logging.WARNING : "WARNING: %(message)s",
#                logging.ERROR   : "ERROR: %(message)s"}
#     def format(self, record):
# def file_found(filename,force):
# 
# Path: ugali/isochrone/parsec.py
# class ParsecIsochrone(Isochrone):
# class Bressan2012(ParsecIsochrone):
# class Marigo2017(ParsecIsochrone):
#     def z2feh(cls, z):
#     def feh2z(cls, feh):
#     def query_server(self,outfile,age,metallicity):
#     def verify(cls, filename, survey, age, metallicity):
#     def _parse(self,filename):
#     def _parse(self,filename):
# 
# Path: ugali/isochrone/model.py
# def sum_mags(mags, weights=None):
# def jester_mag_v(g_sdss, r_sdss):
#     def __init__(self, **kwargs):
#     def _setup(self, **kwargs):
#     def _parse(self,filename):
#     def get_dirname(self):
#     def todict(self):
#     def distance(self):
#     def sample(self, mode='data', mass_steps=1000, mass_min=0.1, full_data_range=False):
#     def stellar_mass(self, mass_min=0.1, steps=10000):
#     def stellar_luminosity(self, steps=10000):
#     def absolute_magnitude(self, richness=1, steps=1e4):
#     def absolute_magnitude_martin(self, richness=1, steps=1e4, n_trials=1000, mag_bright=None, mag_faint=23., alpha=0.32, seed=None):
#     def simulate(self, stellar_mass, distance_modulus=None, **kwargs):
#     def observableFractionCMDX(self, mask, distance_modulus, mass_min=0.1):
#     def observableFractionCMD(self, mask, distance_modulus, mass_min=0.1):
#     def observableFractionCDF(self, mask, distance_modulus, mass_min=0.1):
#     def observableFractionMMD(self, mask, distance_modulus, mass_min=0.1):
#     def signalMMD(self, mask, distance_modulus, mass_min=0.1, nsigma=5, delta_mag=0.03, mass_steps=1000, method='step'):
#     def histogram2d(self,distance_modulus=None,delta_mag=0.03,steps=10000):
#     def pdf_mmd(self, lon, lat, mag_1, mag_2, distance_modulus, mask, delta_mag=0.03, steps=1000):
#     def pdf(self, mag_1, mag_2, mag_err_1, mag_err_2, 
#             distance_modulus=None, delta_mag=0.03, steps=10000):
#     def raw_separation(self,mag_1,mag_2,steps=10000):
#     def separation(self, mag_1, mag_2):
#         def interp_iso(iso_mag_1,iso_mag_2,mag_1,mag_2):
#     def __init__(self,**kwargs):
#     def __str__(self,indent=0):
#     def z2feh(cls, z):
#     def feh2z(cls, feh):
#     def feh(self):
#     def params2filename(cls,age,metallicity):
#     def filename2params(cls,filename):
#     def create_grid(self,abins=None,zbins=None):
#     def create_tree(self,grid=None):
#     def get_filename(self):
#     def _cache(self,name=None):
#     def _parse(self,filename):
#     def print_info(self,age,metallicity):
#     def query_server(self,outfile,age,metallicity):
#     def verify(cls,filename,survey,age,metallicity):
#     def download(self,age=None,metallicity=None,outdir=None,force=False):
# def absolute_magnitude(distance_modulus,g,r,prob=None):
# class IsochroneModel(Model):
# class Isochrone(IsochroneModel):
#         V = jester_mag_v(sdss_g,sdss_r)
#         V = jester_mag_v(sdss_g, sdss_r)
#             V = jester_mag_v(sdss_g[cut]-iso.distance_modulus,
#                              sdss_r[cut]-iso.distance_modulus)
#     V = g - 0.487*(g - r) - 0.0249


import os
import sys
import glob
import copy
import tempfile
import subprocess
import shutil
import numpy as np
from collections import OrderedDict as odict
    from urllib.parse import urlencode
    from urllib.request import urlopen, Request
    from urllib import urlencode
    from urllib2 import urlopen, Request
from ugali.utils.logger import logger
from ugali.isochrone.parsec import Isochrone
from ugali.isochrone.model import get_iso_dir
        
        params = dict(self.download_defaults)
        params['output'] = dict_output[self.survey]
        params['FeH_value'] = feh
        params['age_value'] = age * 1e9
        if params['age_scale'] == 'log10':
            params['age_value'] = np.log10(params['age_value'])

        server = self.download_url
        url = server + '/iso_form.php'
        # First check that the server is alive
        logger.debug("Accessing %s..."%url)
        urlopen(url,timeout=2)

        #response = requests.post(url,data=params)
        q = urlencode(params).encode('utf-8')
        request = Request(url,data=q)
        response = urlopen(request)
        try:
            fname = os.path.basename(str(response.read()).split('"')[1])
        except Exception as e:
            logger.debug(str(e))
            msg = 'Output filename not found'
            raise RuntimeError(msg)
            
        tmpdir = os.path.dirname(tempfile.NamedTemporaryFile().name)
        tmpfile = os.path.join(tmpdir,fname)

        out = '{0}/tmp/{1}'.format(server, fname)
        cmd = 'wget --progress dot:binary %s -P %s'%(out,tmpdir)

# Path: ugali/utils/logger.py
# class SpecialFormatter(logging.Formatter):
#     FORMATS = {'DEFAULT'       : "%(message)s",
#                logging.WARNING : "WARNING: %(message)s",
#                logging.ERROR   : "ERROR: %(message)s"}
#     def format(self, record):
# def file_found(filename,force):
# 
# Path: ugali/isochrone/parsec.py
# class ParsecIsochrone(Isochrone):
# class Bressan2012(ParsecIsochrone):
# class Marigo2017(ParsecIsochrone):
#     def z2feh(cls, z):
#     def feh2z(cls, feh):
#     def query_server(self,outfile,age,metallicity):
#     def verify(cls, filename, survey, age, metallicity):
#     def _parse(self,filename):
#     def _parse(self,filename):
# 
# Path: ugali/isochrone/model.py
# def sum_mags(mags, weights=None):
# def jester_mag_v(g_sdss, r_sdss):
#     def __init__(self, **kwargs):
#     def _setup(self, **kwargs):
#     def _parse(self,filename):
#     def get_dirname(self):
#     def todict(self):
#     def distance(self):
#     def sample(self, mode='data', mass_steps=1000, mass_min=0.1, full_data_range=False):
#     def stellar_mass(self, mass_min=0.1, steps=10000):
#     def stellar_luminosity(self, steps=10000):
#     def absolute_magnitude(self, richness=1, steps=1e4):
#     def absolute_magnitude_martin(self, richness=1, steps=1e4, n_trials=1000, mag_bright=None, mag_faint=23., alpha=0.32, seed=None):
#     def simulate(self, stellar_mass, distance_modulus=None, **kwargs):
#     def observableFractionCMDX(self, mask, distance_modulus, mass_min=0.1):
#     def observableFractionCMD(self, mask, distance_modulus, mass_min=0.1):
#     def observableFractionCDF(self, mask, distance_modulus, mass_min=0.1):
#     def observableFractionMMD(self, mask, distance_modulus, mass_min=0.1):
#     def signalMMD(self, mask, distance_modulus, mass_min=0.1, nsigma=5, delta_mag=0.03, mass_steps=1000, method='step'):
#     def histogram2d(self,distance_modulus=None,delta_mag=0.03,steps=10000):
#     def pdf_mmd(self, lon, lat, mag_1, mag_2, distance_modulus, mask, delta_mag=0.03, steps=1000):
#     def pdf(self, mag_1, mag_2, mag_err_1, mag_err_2, 
#             distance_modulus=None, delta_mag=0.03, steps=10000):
#     def raw_separation(self,mag_1,mag_2,steps=10000):
#     def separation(self, mag_1, mag_2):
#         def interp_iso(iso_mag_1,iso_mag_2,mag_1,mag_2):
#     def __init__(self,**kwargs):
#     def __str__(self,indent=0):
#     def z2feh(cls, z):
#     def feh2z(cls, feh):
#     def feh(self):
#     def params2filename(cls,age,metallicity):
#     def filename2params(cls,filename):
#     def create_grid(self,abins=None,zbins=None):
#     def create_tree(self,grid=None):
#     def get_filename(self):
#     def _cache(self,name=None):
#     def _parse(self,filename):
#     def print_info(self,age,metallicity):
#     def query_server(self,outfile,age,metallicity):
#     def verify(cls,filename,survey,age,metallicity):
#     def download(self,age=None,metallicity=None,outdir=None,force=False):
# def absolute_magnitude(distance_modulus,g,r,prob=None):
# class IsochroneModel(Model):
# class Isochrone(IsochroneModel):
#         V = jester_mag_v(sdss_g,sdss_r)
#         V = jester_mag_v(sdss_g, sdss_r)
#             V = jester_mag_v(sdss_g[cut]-iso.distance_modulus,
#                              sdss_r[cut]-iso.distance_modulus)
#     V = g - 0.487*(g - r) - 0.0249


# Path: ugali/isochrone/mesa.py
import os
import sys
import glob
import copy
import tempfile
import subprocess
import shutil
import numpy as np
from collections import OrderedDict as odict
    from urllib.parse import urlencode
    from urllib.request import urlopen, Request
    from urllib import urlencode
    from urllib2 import urlopen, Request
from ugali.utils.logger import logger
from ugali.isochrone.parsec import Isochrone
from ugali.isochrone.model import get_iso_dir

        
        params = dict(self.download_defaults)
        params['output'] = dict_output[self.survey]
        params['FeH_value'] = feh
        params['age_value'] = age * 1e9
        if params['age_scale'] == 'log10':
            params['age_value'] = np.log10(params['age_value'])

        server = self.download_url
        url = server + '/iso_form.php'
        # First check that the server is alive
        logger.debug("Accessing %s..."%url)
        urlopen(url,timeout=2)

        #response = requests.post(url,data=params)
        q = urlencode(params).encode('utf-8')
        request = Request(url,data=q)
        response = urlopen(request)
        try:
            fname = os.path.basename(str(response.read()).split('"')[1])
        except Exception as e:
            logger.debug(str(e))
            msg = 'Output filename not found'
            raise RuntimeError(msg)
            
        tmpdir = os.path.dirname(tempfile.NamedTemporaryFile().name)
        tmpfile = os.path.join(tmpdir,fname)

        out = '{0}/tmp/{1}'.format(server, fname)
        cmd = 'wget --progress dot:binary %s -P %s'%(out,tmpdir)

        logger.debug(cmd)