# Alpha O. Sall
# 03/24/2014

from flask import Flask, request, Response
import json
import requests
from array import *
from Log import Log

def getCephRestApiUrl(request):
    # discover ceph-rest-api URL
    return request.url_root.replace("inkscopeCtrl","ceph-rest-api")

class Pools:
    """docstring for pools"""
    def __init__(self):
        pass

    def newpool_attribute(self, jsonform):
        jsondata = json.loads(jsonform)
        self.name = jsondata['pool_name']
        self.pg_num = jsondata['pg_num']
        self.pgp_num = jsondata['pg_placement_num']
        self.type = jsondata['type']
        self.size = jsondata['size']
        self.min_size = jsondata['min_size']
        self.crash_replay_interval = jsondata['crash_replay_interval']
        self.crush_ruleset = jsondata['crush_ruleset']
        self.erasure_code_profile = jsondata['erasure_code_profile']
        self.quota_max_objects = jsondata['quota_max_objects']
        self.quota_max_bytes = jsondata['quota_max_bytes']

    def savedpool_attribute(self, ind, jsonfile):
        r = jsonfile.json()
        self.name = r['output']['pools'][ind]['pool_name']
        self.pg_num = r['output']['pools'][ind]['pg_num']
        self.pgp_num = r['output']['pools'][ind]['pg_placement_num']
        self.type = r['output']['pools'][ind]['type']
        self.size = r['output']['pools'][ind]['size']
        self.min_size = r['output']['pools'][ind]['min_size']
        self.crash_replay_interval = r['output']['pools'][ind]['crash_replay_interval']
        self.crush_ruleset = r['output']['pools'][ind]['crush_ruleset']
        self.erasure_code_profile = r['output']['pools'][ind]['erasure_code_profile']
        self.quota_max_objects = r['output']['pools'][ind]['quota_max_objects']
        self.quota_max_bytes = r['output']['pools'][ind]['quota_max_bytes']

    def register(self):
        uri = self.cephRestApiUrl+'osd/pool/create?pool='+self.name+'&pool_type='+self.type+'&pg_num='+str(self.pg_num)+'&pgp_num='+str(self.pgp_num)
        if self.erasure_code_profile != "":
            uri += '&erasure_code_profile='+self.erasure_code_profile
        register_pool = requests.put(uri)
        # if newpool.register().status_code != 200:
        # #     return 'Error '+str(r.status_code)+' on creating pools'
        # else:



def getindice(id, jsondata):
    r = jsondata.content
    r = json.loads(r)
    mypoolsnum = array('i',[])
    for i in r['output']['pools']:
        mypoolsnum.append(i[u'pool'])
    if id not in  mypoolsnum:
        return "Pool not found"

    else:
        for i in range(len(mypoolsnum)):
            if mypoolsnum[i]==id:
                id=i
        return id

def getpoolname(ind, jsondata):

    r = jsondata.json()
    poolname = r['output']['pools'][ind]['pool_name']

    return str(poolname)

def checkpool(pool_id, jsondata):
    skeleton = {'status':'','output':{}}
    if isinstance(pool_id, int):
        ind = getindice(pool_id, jsondata)
        id = ind
        if id == "Pool id not found":
            skeleton['status'] = id
            result = json.dumps(skeleton)
            return Response(result, mimetype='application/json')
        else:
            skeleton['status'] = 'OK'
            result = json.dumps(skeleton)
            return Response(result, mimetype='application/json')
    if isinstance(pool_id, str):
        r = jsondata.content
        r = json.loads(r)
        mypoolsname = array('i',[])
        for i in r['output']:
            mypoolsname.append(i[u'poolname'])
        if pool_id not in  mypoolsname:
            skeleton['status'] = 'OK'
            result = json.dumps(skeleton)
            return Response(result, mimetype='application/json')
        else:
            skeleton['status'] = pool_id+'already exits. Please enter a new pool name'
            result = json.dumps(skeleton)
            return Response(result, mimetype='application/json')

def geterrors(url, methods):
    try:
        if methods == 'GET':
            r = requests.get(url)
        else:
            r = requests.put(url)
    except HTTPError, e:
        return 'Error '+str(r.status_code)
    else:
        return  'ok'


# @app.route('/pools/', methods=['GET','POST'])
# @app.route('/pools/<int:id>', methods=['GET','DELETE','PUT'])
def pool_manage(id):
    cephRestApiUrl = getCephRestApiUrl(request);
    if request.method == 'GET':
        if id == None:

            r = requests.get(cephRestApiUrl+'osd/lspools.json')

            if r.status_code != 200:
                return Response(r.raise_for_status())
            else:
                r = r.content
                return Response(r, mimetype='application/json')

        else:
            data = requests.get(cephRestApiUrl+'osd/dump.json')
            if data.status_code != 200:
                return 'Error '+str(data.status_code)+' on the request getting pools'
            else:

                ind = getindice(id, data)
                id = ind
                skeleton = {'status':'','output':{}}
                if id == "Pool id not found":