# -*- coding: utf-8 -*-
"""Access_OSIRIS_data_with_KOA.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1aXic1m2rES9DmhnhgZ2JqSwgPUCdWl-E

This notebook is a brief guide of downloading OSIRIS raw (level 0)
data in a given period. It requires PI credentials to access
proprietary data. For more detail about PyKOA, please see:
http://koa.ipac.caltech.edu/UserGuide/PyKOA/notebooks/PyKOA_OSIRIS_introduction.html

First, we need to install the KOA python client PyKOA. This line can
be removed if PyKOA is already installed.
"""

!pip install pykoa

"""The next steop is to import pre-requisite packages"""

import sys
import io
import os
from pykoa.koa import Koa
from astropy.table import Table,Column

"""Then we need to assign directory that stores the query results:"""

try:
    os.mkdir('./output')
except:
    print(" Directory exists already", flush=True)

"""After that, we use a cookie for KOA log in. We can also spell out
the credentials, but for security purpose, it is better to enter the
userid and password interactively"""

Koa.login ('./tapcookie.txt')
#Koa.login ('./tapcookie.txt', userid='clee', password='salami')

"""We can then proceed to query OSIRIS data taken in a given
period. Note the time period is specified in UT date. The output table
will be saved in the designated directory and in IPAC table format."""

Koa.query_datetime ('osiris', \
    '2021-07-02 00:00:00/2021-07-02 23:59:59', \
    './output/osiris_daterange.tbl', overwrite=True, format='ipac', \
    cookiepath='./tapcookie.txt')

rec = Table.read ('./output/osiris_daterange.tbl',format='ipac')
print (rec)

"""Once we have the query result, we can download files to the
designated directory, in this case to dnload_dir_osiris/. If the
download function is called several times, it will check the
designated directory and only download new files."""

Koa.download ('./output/osiris_daterange.tbl',
    'ipac', \
    'dnload_dir_osiris' )
#    'dnload_dir_osiris', \
#    start_row=0, \
#    end_row = 2)