
import logging

logging.basicConfig(level=logging.DEBUG)

import pandas as pd
import numpy as np

from SAE.datakit.bundle import BundleCollection

from bokeh.plotting import figure
from bokeh.models import Plot, ColumnDataSource
from bokeh.server.app import bokeh_app
from bokeh.server.utils.plugins import object_page
from bokeh.properties import ( Instance, Bool, Any, String,List )
from bokeh.models.widgets import *

_DBPATH = 'm5db.db'

class ManifestPanel(Panel):
    plot = Instance(Plot)
    data = Instance(ColumnDataSource)

    @classmethod
    def create(cls,manifest):
        o = cls(title=manifest.tablename,child=VBox())
#        o.data = ColumnDataSource(data=manifest.dataframe())
        o.data = ColumnDataSource(data={'x':range(0,10),'y':range(0,10)})        
        o.plot = figure(title=manifest.tablename,
                        plot_width=1200,
                        plot_height=600,
                        x_axis_type='datetime')

        o.plot.line('x','y',source=o.data)
        o.child.children.append(o.plot)
        o._manifest = manifest
        return o
        
def ManifestPanelFactory(manifest):
    plot = figure(title=manifest.tablename,
                  plot_width=1200,
                  plot_height=600,
                  x_axis_type='datetime')
    #data = ColumnDataSource(data=manifest.dataframe())
    data = ColumnDataSource(data={'x':range(0,10),'y':range(0,10)})        
    plot.line('x','y',source=data)
    o = Panel(title=manifest.tablename,child=VBox(children=[plot]))
    return o

class Plots(VBox):
    extra_generated_classes = [["Plots","Plots","VBox"]]

    dbpath = String
    @classmethod
    def create(cls,dbpath,initialTab=0):
        b = BundleCollection(dbpath).defaultBundle
#        panels = [ManifestPanel.create(m) for m in b.manifests if m.isData]
        panels = [ManifestPanelFactory(m) for m in b.manifests if m.isData]
        o = cls(children=[Tabs(tabs=panels,active=0)])
        o.dbpath = dbpath
        return o

    @property
    def bundleCollection(self):
        try:
            return self._bc
        except AttributeError:
            pass
        self._bc = BundleCollection(self.dbpath)
        return self._bc
    
@bokeh_app.route("/SAE/Plots/")
@object_page("Plots")
def make_Plots():
    app = Plots.create(_DBPATH)
    return app
