from __future__ import absolute_import
import numpy as np
import time

from redis import StrictRedis,Redis
from celery import result as celery_result
import json

redis_connection = StrictRedis()

import redis
import threading
import requests

from rowsandall_app.settings import SITE_URL
from rowsandall_app.settings_dev import SITE_URL as SITE_URL_DEV

def getvalue(data):
    perc = 0
    total = 1
    done = 0
    id = 0
    session_key = 'noot'
    for i in data.iteritems():
        if i[0] == 'total':
            total = float(i[1])
        if i[0] == 'done':
            done = float(i[1])
        if i[0] == 'id':
            id = i[1]
        if i[0] == 'session_key':
            session_key = i[1]

    return total,done,id,session_key



def longtask(aantal,jobid=None,debug=False,
             session_key=None):
    counter = 0

    channel = 'tasks'
    for i in range(aantal):
        time.sleep(1)
        counter += 1
        if counter > 10:
            counter = 0
            if debug:
                progress = 100.*i/aantal
                if jobid != None:
                    redis_connection.publish(channel,json.dumps(
                        {
                            'done':i,
                            'total':aantal,
                            'id':jobid,
                            'session_key':session_key,
                            }
                        ))



    return 1

def longtask2(aantal,jobid=None,debug=False,secret=''):
    counter = 0

    channel = 'tasks'
    for i in range(aantal):
        time.sleep(1)
        counter += 1
        if counter > 10:
            counter = 0
            progress = int(100.*i/aantal)
            if debug:
                print progress
            if jobid != None:
                if debug:
                    url = SITE_URL_DEV
                else:
                    url = SITE_URL
                url += "/rowers/record-progress/"
                url += str(progress)+"/"+jobid
                post_data = {"secret":secret}
                s = requests.post(url, data=post_data)
                if debug:
                    print url
                    print s


    return 1
