#!/usr/bin/env python
# -*- coding: utf-8 -*-
from gevent import monkey
monkey.patch_all()

from os import sys, path
import schedule
from time import sleep

from bottle.ext.mongo import MongoPlugin

sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from mining.bin.cube import run
from mining.utils import conf, log_it


log_it("START", "bin-scheduler")


def job(slug):
    log_it("START JOB: {}".format(slug), "bin-scheduler")
    run(slug)
    log_it("END JOB: {}".format(slug), "bin-scheduler")


def rules(cube, scheduler_type='minutes', scheduler_interval=59):
    if scheduler_type:
        scheduler_type = cube.get('scheduler_type', 'minutes')
    if scheduler_interval:
        scheduler_interval = cube.get('scheduler_interval', 59)

    log_it("START REGISTER", "bin-scheduler")
    log_it("cube: {}".format(cube.get('slug')), "bin-scheduler")
    log_it("type: {}".format(scheduler_type), "bin-scheduler")
    log_it("interval: {}".format(scheduler_interval), "bin-scheduler")
    log_it("END REGISTER", "bin-scheduler")

    t = {}
    if scheduler_type == 'minutes':
        t = schedule.every(int(scheduler_interval)).minutes
    elif scheduler_type == 'hour':
        t = schedule.every().hour
    elif scheduler_type == 'day':
        t = schedule.every().day

    try:
        t.do(job, slug=cube.get('slug'))
    except Exception, e:
        log_it("ERROR {}: {}".format(cube.get('slug'), e))

    return True


mongo = MongoPlugin(
    uri=conf("mongodb")["uri"],
    db=conf("mongodb")["db"],
    json_mongo=True).get_mongo()

register = []
for cube in mongo['cube'].find({'scheduler_status': True}):
    rules(cube)
    run(cube['slug'])
    register.append(cube['slug'])

for dashboard in mongo['dashboard'].find({'scheduler_status': True}):
    elements = [e['id'] for e in dashboard['element']]
    for e in elements:
        element = mongo['element'].find_one({'slug': e})
        cube = mongo['cube'].find_one({'slug': element['cube']})
        rules(cube, dashboard['scheduler_type'],
              dashboard['scheduler_interval'])
        run(cube['slug'])
        register.append(cube['slug'])

while True:
    for cube in mongo['cube'].find({'scheduler_status': True}):
        if cube['slug'] not in register:
            rules(cube)

    for dashboard in mongo['dashboard'].find({'scheduler_status': True}):
        elements = [e['id'] for e in dashboard['element']]
        for e in elements:
            element = mongo['element'].find_one({'slug': e})
            cube = mongo['cube'].find_one({'slug': element['cube']})
            if cube['slug'] not in register:
                rules(cube, dashboard['scheduler_type'],
                      dashboard['scheduler_interval'])
                register.append(cube['slug'])

    schedule.run_pending()
    sleep(1)

@@ -361,24 +361,49 @@
 scheduler%22)%0A
+onrun = %7B%7D%0Aregister = %5B%5D%0A
 %0A%0Adef job(sl
@@ -600,16 +600,42 @@
 erval=59
+,%0A          dashboard=None
 ):%0A    i
@@ -1144,33 +1144,35 @@
 nutes':%0A        
-t
+env
  = schedule.ever
@@ -1197,16 +1197,32 @@
 terval))
+%0A        t = env
 .minutes
@@ -1257,33 +1257,35 @@
 'hour':%0A        
-t
+env
  = schedule.ever
@@ -1287,16 +1287,32 @@
 .every()
+%0A        t = env
 .hour%0A  
@@ -1351,17 +1351,19 @@
         
-t
+env
  = sched
@@ -1373,16 +1373,32 @@
 .every()
+%0A        t = env
 .day%0A%0A  
@@ -1445,16 +1445,190 @@
 slug'))%0A
+        jobn = cube.get(%22slug%22)%0A        if dashboard:%0A            jobn = u%22%7B%7D-%7B%7D%22.format(cube.get(%22slug%22), dashboard)%0A        onrun%5Bjobn%5D = env%0A        register.append(jobn)%0A
     exce
@@ -1839,30 +1839,16 @@
 ongo()%0A%0A
-register = %5B%5D%0A
 for cube
@@ -1940,42 +1940,8 @@
 g'%5D)
-%0A    register.append(cube%5B'slug'%5D)
 %0A%0Afo
@@ -2333,46 +2333,8 @@
 g'%5D)
-%0A        register.append(cube%5B'slug'%5D)
 %0A%0Awh
@@ -2922,54 +2922,795 @@
 al'%5D
-)%0A                register.append(cube%5B'slug'%5D
+,%0A                      dashboard%5B'slug'%5D)%0A%0A    for cube in mongo%5B'cube'%5D.find(%7B'scheduler_status': False%7D):%0A        if cube%5B'slug'%5D in register:%0A            schedule.cancel_job(onrun%5Bcube%5B'slug'%5D%5D)%0A            del onrun%5Bcube%5B'slug'%5D%5D%0A            register.remove(cube%5B'slug'%5D)%0A%0A    for dashboard in mongo%5B'dashboard'%5D.find(%7B'scheduler_status': False%7D):%0A        elements = %5Be%5B'id'%5D for e in dashboard%5B'element'%5D%5D%0A        for e in elements:%0A            element = mongo%5B'element'%5D.find_one(%7B'slug': e%7D)%0A            cube = mongo%5B'cube'%5D.find_one(%7B'slug': element%5B'cube'%5D%7D)%0A            jobn = u%22%7B%7D-%7B%7D%22.format(cube%5B'slug'%5D, dashboard%5B'slug'%5D)%0A            if jobn in register:%0A                schedule.cancel_job(onrun%5Bjobn%5D)%0A                del onrun%5Bjobn%5D%0A                register.remove(jobn
 )%0A%0A 

Fix bug to remove ondemand cube to process on scheduler