# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# to integrate SkyMapper and VLASS image retrieving service
# function: 1. get URL 2. download fits for images with URL

from astropy.io import fits
from astropy.io import ascii
import matplotlib.pyplot as plt

# special function for downloading, can be replaced by other similars
from astropy.utils.data import download_file

# +
import pandas as pd 
from urllib.request import urlopen

def get_deepest_skymapper_filename(ra, dec, size, bands='g'):
    pass


def get_skymapper_filenames(ra, dec, size, bands='g'):
    """

    :param ra:
    :param dec:
    :param bands:
    :return:
    """
    url_base = 'http://api.skymapper.nci.org.au/public/siap/dr2/query?'
    skymapper_url = url_base + 'POS={},{}&SIZE={}&BAND={}'.format(ra, dec, size, bands) + '&FORMAT=GRAPHIC&RESPONSEFORMAT=CSV'

    
    # read the catalogue of fits
    # _catalogue is a temporary file from query of SkyMapper DR2
#     _catalogue = urlopen(skymapper_url)
#     data = (_catalogue.read().decode('utf-8'))
    
    image_df = pd.read_csv(urlopen(skymapper_url))
    print(image_df)
#     image_df.query('image_type == "main"', inplace=True)
    image_df.sort_values(['exptime','mjd_obs'], inplace=True)
    print(image_df)
    return image_df.loc[image_df.index[-1],'get_fits']
    
#     for i in range(len(data['get_fits'])):
#         bands.append(data[i]['band'])
#         image_data.append(fits.getdata(data[i]['get_fits']))
#         mjd_obs.append(data[i]['mjd_obs'])


#     if len(bands) > 0:
#         return bands, image_data, mjd_obs
#     else:
#         print("No SkyMapper DR2 image is available for this position.")
#         return None
# -

def get_skymapper_image_url(ra, dec, fov, bands='g', verbosity=0):
    """

    :param ra:
    :param dec:
    :param fov:
    :param bands:
    :param verbosity:
    :return:
    """


    # Convert field of view in arcsecond to arbitrary size (0.01 'size' = 36 arcsecs)
    size = fov / 3600

    bands, image_data, mjd_obs = get_skymapper_filenames(ra, dec, size, bands)

    if image_data is not None:
        
        url_list = image_data

        return url_list, bands, mjd_obs
    else:
        return None

# an example:
#
#
# all we need for inputs: ra, dec, bands, fov (in arcsecs)

# +
ra = 239.7124; dec = -07.4026; band = 'z'; fov = 100
# all we need for input here

get_skymapper_filenames(ra, dec, fov/3600, bands='z')

# +
ra = 113.917764; dec = -39.132592; band = 'z'; fov = 100
# all we need for input here

# url, bands, mjd_obs = get_skymapper_image_url(ra, dec, fov, band,
#                           verbosity=0)
3746*12
# -

33000/12.

print(len(url))
plt.imshow(url[2], cmap='gray')


# part of 'get_photometry' with skymapper querying feature

def get_photometry(table, ra_col_name, dec_col_name, surveys, bands, image_folder_path,
                   fovs, verbosity=0):


    table, table_format = check_if_table_is_pandas_dataframe(table)

    table.loc[:, 'temp_object_name'] = ut.coord_to_name(table.loc[:,
                                                 ra_col_name].values,
                                                 table.loc[
                                                 :,dec_col_name].values,
                                                 epoch="J")

    for jdx, band in enumerate(bands):

        survey = surveys[jdx]
        fov = fovs[jdx]

        # Hack to check if the issue is with opening too many services
        if survey == "desdr1":
            # Set the DES DR1 NOAO sia url
            def_access_url = "https://datalab.noao.edu/sia/des_dr1"
            svc = sia.SIAService(def_access_url)
        else:
            svc = None

        for idx in table.index:
            ra = table.loc[idx, ra_col_name]
            dec = table.loc[idx, dec_col_name]


            if survey == "ps1" and band in ["g", "r", "i", "z", "y"]:
                img_name = table.temp_object_name[idx] + "_" + survey + "_" + \
                           band + "_fov" + '{:d}'.format(fov)

                file_path = image_folder_path + '/' + img_name + '.fits'
                file_exists = os.path.isfile(file_path)

                if file_exists is not True:
                    url_list = get_ps1_image_cutout_url(ra, dec, fov=fov,
                                                   bands=band,
                                                   verbosity=verbosity)
                    if url_list is not None:
                        url = url_list[0]
                    else:
                        url = None

                else:
                    url = None


            elif survey == "SKYMAPPER":

                img_name = table.temp_object_name[idx] + "_" + survey + "_" + \
                           band + "_fov" + '{:d}'.format(fov)

                file_path = image_folder_path + '/' + img_name + '.fits'
                file_exists = os.path.isfile(file_path)

                if file_exists is not True:
                    url = get_skymapper_image_url(ra, dec, fov, band,
                                              verbosity=verbosity)

                else:
                    url = None


            else:
                raise ValueError("Survey and band name not recognized: {} {}. "
                                 "\n "
                                 "Possible survey names include: desdr1, ps1,"
                                 "vhsdr6, vikingdr5,"
                                 "unwise-allwise, unwise-neo1, unwise-neo2, "
                                 "unwise-neo3, unwise-neo4, unwise-neo5, "
                                 "unwise-neo6".format(survey, band))

            if url is not None:
                download_image(url, image_name=img_name, image_folder_path=image_folder_path,
                               verbosity=verbosity)


StarcoderdataJupyterScriptsDedupFiltered