from __future__ import absolute_import, division, print_function

import os
import json

from glue.core import Subset


DISPATCH = {}


def save_page(page, page_number, label, subset):
    """ Convert a tab of a glue session into a D3PO page

    :param page: Tuple of data viewers to save
    :param label: Tab label
    """
    result = {}

    # layout settings
    result['grid'] = {'nRows': 1, 'nColumns': len(page)}
    result['name'] = str(label)
    result['caption'] = 'Generated by Glue'

    # style settings
    d = page[0]._data[0]
    unselected = dict(opacity=d.style.alpha,
                      size=d.style.markersize / 2,
                      color=d.style.color)
    result['markerStyle'] = dict(unselected=unselected)

    if subset is not None:
        s = subset.style
        selected = dict(opacity=s.alpha, size=s.markersize / 2, color=s.color)
        result['markerStyle']['selected'] = selected
        result['selection'] = {'type': 'booleanColumn',
                               'columnName': 'selection_%i' % page_number}
    result['histogramStyle'] = result['markerStyle']

    # save each plot
    result['plots'] = list(map(save_plot, page, range(len(page))))

    return result


def save_plot_base(plot, index):
    result = {}
    result['gridPosition'] = [0, index]
    return result


def save_plot(plot, index):
    typ = type(plot)
    return DISPATCH[typ](plot, index)


def save_scatter(plot, index):
    """ Convert a single glue scatter plot to a D3PO plot

    :param plot: Glue scatter plot
    :class:`~glue.viewers.scatter.qt.ScatterViewer`
    :param index: 1D index of plot on the page
    :type index: int

    :rtype: json-serializable dict
    """
    result = save_plot_base(plot, index)
    result['type'] = 'scatter'
    result['xAxis'] = dict(columnName=plot.state.x_att.label,
                           range=[float(plot.state.x_min), float(plot.state.x_max)])
    result['yAxis'] = dict(columnName=plot.state.y_att.label,
                           range=[float(plot.state.y_min), float(plot.state.y_max)])
    # XXX log scales
    return result


def save_histogram(plot, index):
    """ Convert a single histogram to a D3PO plot

    :param plot: Glue histogram
    :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer`

    :param index: 1D index of plot on the page
    :type index: int

    :rtype: json-serializable dict
    """
    result = save_plot_base(plot, index)
    result['type'] = 'histogram'
    result['xAxis'] = dict(columnName=plot.state.x_att.label,
                           bins=int(plot.state.hist_n_bin),
                           range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)])
    # XXX normed, cumultive, log
    return result


def stage_subsets(application):
    """
    Return a tuple of the subset to use for each stage/tab,
    or None if the tab has no subset

    If more than one subset is used per stage/tab, returns None
    """
    result = []
    for page in application.viewers:
        subset = None
        for viewer in page:
            for layer_artist in viewer.layers:
                if not layer_artist.visible:
                    continue
                s = layer_artist.layer
                if not isinstance(s, Subset):
                    continue
                if subset is not None and s is not subset:
                    return None
                if subset is None:
                    subset = s
        result.append(subset)
    return tuple(result)


def can_save_d3po(application):
    """
    Check whether an application can be exported to D3PO.

    Raises an exception if not
    """
    dc = application.session.data_collection

    if len(dc) != 1:
        raise ValueError("D3PO Export only supports a single dataset")

    for tab in application.viewers:
        for viewer in tab:
            if not isinstance(viewer, tuple(DISPATCH.keys())):
                raise ValueError("D3PO Export only supports scatter "
                                 "and histogram plots")
    if sum(len(tab) for tab in application.viewers) == 0:
        raise ValueError("D3PO Export requires at least one scatterplot "
                         "or histogram")

    if stage_subsets(application) is None:
        raise ValueError("D3PO Export restricted to 0 or 1 subsets visible "
                         "in each tab")


def make_data_file(data, subsets, path):
    """
    Create the data.csv file, given Data and tuple of subsets
    """
    from astropy.table import Table, Column

    data_path = os.path.join(path, 'data.csv')

    t = Table([data[c] for c in data.components],
              names=[c.label for c in data.components])

    for i, subset in enumerate(subsets):
        if subset is None:
            continue
        c = Column(data=subset.to_mask().astype('i'), name='selection_%i' % i)
        t.add_column(c)

    t.write(data_path, format='ascii', delimiter=',')


def save_d3po(application, path, launch=True):
    """Save a Glue session to a D3PO bundle.

    Currently, this has the following restrictions:
    - The Glue session must have only one dataset open, and 0 or 1 subsets
    - Only scatter plots or histograms are present
    - At least one plot is present

    :param application: Glue appication to save
    :param path: Path to directory to save in. Will be created if needed
    """
    if os.path.exists(path) and not os.path.isdir(path):
        os.unlink(path)

    if not os.path.exists(path):
        os.mkdir(path)

    data = application.session.data_collection[0]
    subsets = stage_subsets(application)
    viewers = application.viewers

    # data.csv
    make_data_file(data, subsets, path)

    # states.json
    result = {}
    result['filename'] = 'data.csv'  # XXX don't think this is needed?
    result['title'] = "Glue export of %s" % data.label
    result['states'] = list(map(save_page, application.viewers,
                                range(len(viewers)),
                                application.tab_names,
                                subsets))

    state_path = os.path.join(path, 'states.json')
    with open(state_path, 'w') as outfile:
        json.dump(result, outfile, indent=2, sort_keys=True)

    # index.html
    html_path = os.path.join(path, 'index.html')
    with open(html_path, 'w') as outfile:
        outfile.write(HTML)

    # show the result
    if launch:
        launch_d3po(path)


def launch_d3po(path):
    """Start a server to view an exported D3PO bundle, and open a browser.

    :param path: The TLD of the bundle
    """
    from glue.external.six.moves.socketserver import TCPServer
    from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler
    from random import randrange
    from socket import error
    import webbrowser
    from threading import Thread

    os.chdir(path)

    while True:
        try:
            PORT = randrange(8000, 9000)
            server = TCPServer(("", PORT), SimpleHTTPRequestHandler, False)
            server.allow_reuse_address = True
            server.server_bind()
            break
        except error:  # port already taken
            pass

    print('Serving D3PO on port 0.0.0.0:%i' % PORT)
    server.server_activate()

    thread = Thread(target=server.serve_forever)
    thread.setDaemon(True)  # do not prevent shutdown
    thread.start()
    webbrowser.open('http://0.0.0.0:%i' % PORT)


def setup():
    from glue.config import exporters
    exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory')


HTML = """
<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8" />

<link rel="stylesheet" type="text/css" href="http://d3po.org/static/css/style.css">
<link rel="stylesheet" type="text/css" href="http://d3po.org/static/css/d3po.css">
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'>

<style>
#footer {
position: fixed;
bottom: 0;
right: 0;
}
</style>
<!-- not to be confused with Planet Telex -->

<!-- Javscript dependencies -->
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="http://d3po.org/static/js/util.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://d3po.org/static/js/d3po.js"></script>
<script src="http://d3po.org/static/js/d3po.init.js"></script>
</head>

<body>
<div id="svg"><svg></svg></div>
<div id="controls">
<ul class="navigation">
</ul>
</div>
<div id="caption"></div>

<div id="footer">
More information: <a href="http://d3po.org">d3po.org</a>
</div>

<script type="text/javascript">
$(document).ready(function() {
initialize('states.json', 'data.csv');
}
);
</script>
</body>
</html>
"""

try:
    from glue.viewers.scatter.qt import ScatterViewer
    from glue.viewers.histogram.qt import HistogramViewer
except ImportError:
    pass
else:
    DISPATCH[ScatterViewer] = save_scatter
    DISPATCH[HistogramViewer] = save_histogram

[((153, 16, 153, 46), 'os.path.join', 'os.path.join', ({(153, 29, 153, 33): 'path', (153, 35, 153, 45): '"""data.csv"""'}, {}), "(path, 'data.csv')", False, 'import os\n'), ((155, 8, 156, 55), 'astropy.table.Table', 'Table', (), '', False, 'from astropy.table import Table, Column\n'), ((200, 17, 200, 50), 'os.path.join', 'os.path.join', ({(200, 30, 200, 34): 'path', (200, 36, 200, 49): '"""states.json"""'}, {}), "(path, 'states.json')", False, 'import os\n'), ((205, 16, 205, 48), 'os.path.join', 'os.path.join', ({(205, 29, 205, 33): 'path', (205, 35, 205, 47): '"""index.html"""'}, {}), "(path, 'index.html')", False, 'import os\n'), ((226, 4, 226, 18), 'os.chdir', 'os.chdir', ({(226, 13, 226, 17): 'path'}, {}), '(path)', False, 'import os\n'), ((241, 13, 241, 48), 'threading.Thread', 'Thread', (), '', False, 'from threading import Thread\n'), ((244, 4, 244, 47), 'webbrowser.open', 'webbrowser.open', ({(244, 20, 244, 46): "('http://0.0.0.0:%i' % PORT)"}, {}), "('http://0.0.0.0:%i' % PORT)", False, 'import webbrowser\n'), ((249, 4, 249, 72), 'glue.config.exporters.add', 'exporters.add', (), '', False, 'from glue.config import exporters\n'), ((178, 7, 178, 27), 'os.path.exists', 'os.path.exists', ({(178, 22, 178, 26): 'path'}, {}), '(path)', False, 'import os\n'), ((179, 8, 179, 23), 'os.unlink', 'os.unlink', ({(179, 18, 179, 22): 'path'}, {}), '(path)', False, 'import os\n'), ((181, 11, 181, 31), 'os.path.exists', 'os.path.exists', ({(181, 26, 181, 30): 'path'}, {}), '(path)', False, 'import os\n'), ((182, 8, 182, 22), 'os.mkdir', 'os.mkdir', ({(182, 17, 182, 21): 'path'}, {}), '(path)', False, 'import os\n'), ((202, 8, 202, 60), 'json.dump', 'json.dump', (), '', False, 'import json\n'), ((178, 36, 178, 55), 'os.path.isdir', 'os.path.isdir', ({(178, 50, 178, 54): 'path'}, {}), '(path)', False, 'import os\n'), ((230, 19, 230, 40), 'random.randrange', 'randrange', ({(230, 29, 230, 33): '8000', (230, 35, 230, 39): '9000'}, {}), '(8000, 9000)', False, 'from random import randrange\n'), ((231, 21, 231, 75), 'glue.external.six.moves.socketserver.TCPServer', 'TCPServer', ({(231, 31, 231, 41): "('', PORT)", (231, 43, 231, 67): 'SimpleHTTPRequestHandler', (231, 69, 231, 74): 'False'}, {}), "(('', PORT), SimpleHTTPRequestHandler, False)", False, 'from glue.external.six.moves.socketserver import TCPServer\n')]