def editPartner(request):
    if 'user_data' not in request.session:
        return HttpResponseRedirect("/login")

    staff_id = str(
        request.session['user_data']['user_info']['staff_and_agents_id'])
    post_data = request.POST
    # send request to api
    params = '{"staff_id":' + staff_id + ', "data":' + json.dumps(
        post_data) + '}'
    r = Request()
    r = r.post(params, 'staff/editStaff',
               request.session['user_data']['tokens']['access_token'])
    data = r.json()
    if 'staff_and_agents_id' in post_data and post_data[
            'staff_and_agents_id'] != '':
        if data['data']['staff']['staff_updated']:
            msg = 'Staff  Updated'
            data = {'alert': 'success', 'message': msg}
        else:
            data = {'alert': 'error', 'message': 'Staff not updated'}
    else:
        if data['data']['staff']['staff_created']:
            msg = 'Staff created'
            data = {'alert': 'success', 'message': msg}
        else:
            data = {'alert': 'error', 'message': 'Staff not creaded'}
    return HttpResponse(json.dumps(data))
def createTollfree(request, clientId):
    if request.method == "POST":
        staff_id = str(
            request.session['user_data']['user_info']['staff_and_agents_id'])
        post_data = request.POST
        params = '{"staff_id":' + staff_id + ', "client_id":' + clientId + ', "data":' + json.dumps(
            post_data) + '}'
        if 'client_toll_free_id' in post_data and post_data[
                'client_toll_free_id'] != '':
            url = 'clients/updateTollfree'
        else:
            url = 'clients/createTollfree'

        r = Request()
        r = r.post(params, url,
                   request.session['user_data']['tokens']['access_token'])
        data = r.json()

        if 'client_toll_free_id' in post_data and post_data[
                'client_toll_free_id'] != '':
            if data['data']['tollfree']['tollfree_updated']:
                msg = 'Tollfree Updated'
                data = {'alert': 'success', 'message': msg}
            else:
                data = {'alert': 'error', 'message': 'Tollfree not updated'}
        else:
            if data['data']['tollfree']['tollfree_created']:
                msg = 'Tollfree created'
                data = {'alert': 'success', 'message': msg}
            else:
                data = {'alert': 'error', 'message': 'Tollfree not creaded'}

        return HttpResponse(json.dumps(data))
def createWhiteLabel(request, clientId):
    if request.method == "POST":
        staff_id = str(
            request.session['user_data']['user_info']['staff_and_agents_id'])
        post_data = request.POST
        params = '{"staff_id":' + staff_id + ', "client_id":' + clientId + ', "data":' + json.dumps(
            post_data) + '}'
        if 'wl_client_id' in post_data and post_data['wl_client_id'] != '':
            url = 'clients/updateWhiteLabel'
        else:
            url = 'clients/createWhiteLabel'

        r = Request()
        r = r.post(params, url,
                   request.session['user_data']['tokens']['access_token'])
        data = r.json()

        if 'wl_client_id' in post_data and post_data['wl_client_id'] != '':
            if data['data']['white_label']['whitelabel_updated']:
                msg = 'Client White Label Updated'
                data = {
                    'alert': 'success',
                    'message': msg,
                    'action': 'createWl'
                }
            else:
                data = {
                    'alert': 'error',
                    'message': 'Client White Label not updated'
                }
            return HttpResponse(json.dumps(data))
def proccessLogin(request):
    if request.method == "POST":
        if (request.POST['account'] and request.POST['pass']):
            try:
                username = request.POST['account']
                password = request.POST['pass']

                # send request to api
                params = '{"username":'******',"password":"******"}'
                r = Request()
                r = r.post(params, 'login')
                data = r.json()
                if data['isSuccess'] and checkUserType(
                        data['data']['user_info']['type']):
                    # save tokens in session
                    request.session['user_data'] = data['data']
                    return redirect("maintainAccountView", client_id=608)
                else:
                    request.session['errors'] = data['errors']
                    return HttpResponseRedirect("/login")
            except ValueError:
                request.session['error'] = 'Account and Password do not match'
        else:
            request.session['error'] = 'Account and Password do not match'
    else:
        request.session['error'] = 'Invalid Request Method'
    return HttpResponseRedirect("/login")
def getWhitelabel(request, clientId):
    staff_id = str(
        request.session['user_data']['user_info']['staff_and_agents_id'])

    params = {"staff_id": staff_id, "client_id": clientId}

    # send request to api
    r = Request()
    if request.GET['wl_enabled'] and request.GET['wl_enabled'] == 'False':

        if 'action' in request.GET and request.GET['action'] == 'read':
            return render(request,
                          'portal/account/controls_sidebar/wl_form.html')

        r = r.post(json.dumps(params), 'prices/getDefaultPrices',
                   request.session['user_data']['tokens']['access_token'])
        data = r.json()
        data['data']['prices_default']['client_id'] = clientId
        return render(request,
                      'portal/account/controls_sidebar/enable_wl.html',
                      {'white_label': data['data']['prices_default']})

    r = Request()
    r = r.get(json.dumps(params), 'clients/getWhitelabel',
              request.session['user_data']['tokens']['access_token'])
    data = r.json()
    if 'action' in request.GET and request.GET['action'] == 'read':
        return render(request, 'portal/account/controls_sidebar/wl_form.html',
                      {'white_label': data['data']['white_label']})
    else:
        return render(request,
                      'portal/account/controls_sidebar/enable_wl.html',
                      {'white_label': data['data']['white_label']})
def createAccount(request):
    if request.method == "POST":
        staff_id = str(
            request.session['user_data']['user_info']['staff_and_agents_id'])
        # send request to api
        post_data = request.POST
        if 'client_id' in post_data and post_data['client_id'] != "":
            url = "clients/edit"
        else:
            url = "clients/create"

        params = '{"staff_id":' + staff_id + ', "data":' + json.dumps(
            post_data) + '}'
        r = Request()
        r = r.post(params, url,
                   request.session['user_data']['tokens']['access_token'])
        data = r.json()
        if 'client_id' in data['data'][
                'client'] and data['data']['client']['client_id'] != 0:
            msg = 'Account created with id : ' + str(
                data['data']['client']['client_id'])
            data = {'alert': 'success', 'message': msg}
        elif 'client_updated' in data['data']['client']:
            data = {'alert': 'success', 'message': "Account Updated"}
        else:
            data = {'alert': 'error', 'message': data['data']['client']['msg']}
        return HttpResponse(json.dumps(data))
def searchClient(request):
    if request.method == "POST":
        if 'user_data' not in request.session:
            return HttpResponseRedirect("/login")

        staff_id = str(
            request.session['user_data']['user_info']['staff_and_agents_id'])
        # user search string
        search_str = request.POST['search_str']
        params = '{"staff_id":' + staff_id + ', "limit":"20", "search_str":"' + search_str + '"}'
        r = Request()
        r = r.post(params, 'clients',
                   request.session['user_data']['tokens']['access_token'])
        data = r.json()
        return render(request, 'portal/components/search_result.html',
                      {'data': data})
def index(request):
    # salt = hex(random.getrandbits(128)).encode()
    # return HttpResponse(len(salt))
    # dk = hashlib.pbkdf2_hmac('sha256',b'mypass',salt, 1000000)
    # return HttpResponse(binascii.hexlify(dk))
    if 'user_data' not in request.session:
        return HttpResponseRedirect("/login")
        # do further call to get user information
    staff_id = str(
        request.session['user_data']['user_info']['staff_and_agents_id'])
    # send request to api
    params = '{"staff_id":' + staff_id + '}'
    r = Request()
    r = r.post(params, 'services',
               request.session['user_data']['tokens']['access_token'])
    data = r.json()
    if 'isSuccess' in data:
        services = {
            'total_amt': 0,
            'toll_calls_amt': 0,
            'local_ditto_amt': 0,
            'fax_amt': 0,
            'st_charges_amt': 0
        }
        if data['data']['services'] is not None:
            for index in data['data']['services']:
                services['total_amt'] += index['invoice_net_amount']
                services['toll_calls_amt'] += index['toll_traffic_amount']
                services['local_ditto_amt'] += index['local_traffic_amount']
                services['fax_amt'] += index['fax_traffic_amount']
                services['st_charges_amt'] += index['standing_charges_amount']

        context = {
            'user_data': request.session['user_data']['user_info'],
            'data': services
        }
        return render(request, 'portal/index.html', context)
    else:
        del request.session['user_data']
        request.session['errors'] = data['errors']
        return HttpResponseRedirect("/login")