
try:
    import urllib2
except:
    import urllib.request as urllib2
import json
from saas_deploy.cluster.addr import CLM_ADDR


def send_dm_request(url, timeout):
    err = ''
    ans = ''
    try:
        req = urllib2.urlopen(CLM_ADDR + url, timeout=timeout)
        ans = req.read().decode('utf-8')
    except urllib2.HTTPError as e:
        err = {'code': e.code, 'answer': str(e.read())}
    except Exception as e:
        err = '%s' % e
    return ans, err


def get_alerts_conf(service, ctype):
    cgis = '&service=' + service + (('&ctype=' + ctype) if ctype else '')
    ans, err = send_dm_request('process_alerts?action=get_conf' + cgis, 15)
    if err:
        return {'success': False, 'error': err}
    res = json.loads(ans)
    if 'success' not in res:
        res['success'] = True
    return res


def clear_left_alerts(dry_run):
    ans, err = send_dm_request('process_alerts?action=clear_left' + ('&dry=1' if dry_run else ''),
                                20 if dry_run else 60)
    return ans, err


def get_actuality(service, ctype):
    url = 'process_alerts?action=check&service=' + service + '&ctype=' + ctype
    ans, err = send_dm_request(url, 20)
    return ans, err


def actualize(service, ctype):
    url = 'process_alerts?action=actualize&service=' + service + '&ctype=' + ctype
    ans, err = send_dm_request(url, 60)
    return ans, err


def actualize_total():
    url = 'total_alerts'
    ans, err = send_dm_request(url, 60)
    return ans, err


def get_sla_table(ctype, component=''):
    url = 'get_sla_table?ctype=' + ctype
    if component:
        url += '&component=' + component
    ans, err = send_dm_request(url, 120)
    return ans, err
