#!/usr/bin/python

# Copyright (C) 2017 Michael Coughlin
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

""".
Gravitational-wave Electromagnetic Optimization

This script generates an optimized list of pointings and content for
reviewing gravitational-wave skymap likelihoods.

Comments should be e-mailed to michael.coughlin@ligo.org.

"""


import os, sys, glob, optparse, shutil, warnings
import copy
import numpy as np
np.random.seed(0)

import healpy as hp
from astropy import table
from astropy import units as u
from astropy import cosmology
from astropy.coordinates import Distance
from astropy.coordinates import SkyCoord
from astropy.coordinates import ICRS

import matplotlib
#matplotlib.rc('text', usetex=True)
matplotlib.use('Agg')
matplotlib.rcParams.update({'font.size': 16})
matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
import matplotlib.pyplot as plt
from matplotlib import cm

import ligo.skymap.distance as ligodist

import gwemopt.utils, gwemopt.plotting
import gwemopt.moc, gwemopt.tiles 
import gwemopt.ztf_tiling

__author__ = "Michael Coughlin <michael.coughlin@ligo.org>"
__version__ = 1.0
__date__    = "6/17/2017"

# =============================================================================
#
#                               DEFINITIONS
#
# =============================================================================

def parse_commandline():
    """@Parse the options given on the command-line.
    """
    parser = optparse.OptionParser(usage=__doc__,version=__version__)

    parser.add_option("--fields", help="Observed fields.", default='/Users/mcoughlin/Code/LIGO/gwemopt/data/ref/suspectrefs_fid1.txt')
    parser.add_option("-c", "--configDirectory", help="GW-EM config file directory.", default ="../config/")
    parser.add_option("-o", "--outputDir", help="output directory",default="../output/refs")

    parser.add_option("-t", "--telescope", help="Telescope.", default ="ZTF")
    parser.add_option("--nside",default=1024,type=int)
    parser.add_option("--rotation",default=240.0,type=float)

    parser.add_option("-v", "--verbose", action="store_true", default=False,
                      help="Run verbosely. (Default: False)")

    opts, args = parser.parse_args()

    # show parameters
    if opts.verbose:
        print >> sys.stderr, ""
        print >> sys.stderr, "running gwemopt_run..."
        print >> sys.stderr, "version: %s"%__version__
        print >> sys.stderr, ""
        print >> sys.stderr, "***************** PARAMETERS ********************"
        for o in opts.__dict__.items():
          print >> sys.stderr, o[0]+":"
          print >> sys.stderr, o[1]
        print >> sys.stderr, ""

    return opts

# =============================================================================
#
#                                    MAIN
#
# =============================================================================

warnings.filterwarnings("ignore")

# Parse command line
opts = parse_commandline()

nside = 256
ra, dec = 0.0, 0.0

quadrant_coords = gwemopt.ztf_tiling.get_ztf_quadrants()

skyoffset_frames = SkyCoord(ra, dec, unit=u.deg).skyoffset_frame()
quadrant_coords_icrs = SkyCoord(
                *np.tile(
                    quadrant_coords[:, np.newaxis, ...],
                    (1, 1, 1)), unit=u.deg,
                frame=skyoffset_frames[:, np.newaxis, np.newaxis]
            ).transform_to(ICRS)
quadrant_xyz = np.moveaxis(quadrant_coords_icrs.cartesian.xyz.value, 0, -1)[0]

for subfield_id, xyz in enumerate(quadrant_xyz):
    ra, dec = hp.vec2ang(xyz, lonlat=True)
    idx = np.where(ra > 180)[0]
    ra[idx] = ra[idx] - 360
    ra = np.append(ra, ra[0])
    dec = np.append(dec, dec[0])
    for ii, (r, d) in enumerate(zip(ra, dec)):
        if ii == 0:
            print('[(%.5f,%.5f)' % (r,d))
        elif ii == 4:
            print('(%.5f,%.5f)]' % (r,d))
        else:
            print('(%.5f,%.5f)' % (r,d))
    print('#')



