def review(request, entity_id):
    user_ver(request, False)
    process_access(request, 'commentbox')

    entity = Entity.objects.get(id=entity_id)
    comment = request.POST['commentbox']
    try:
        selected = request.POST['review']
    except:
        selected = '0'

    if (selected == 'Good' or selected == 'Bad'):
        if (selected == 'Good'):
            entity.positive_review += 1
        else:
            entity.negative_review += 1
        entity.save()

    comment = comment.strip()
    if comment:
        new_comment = EntityComment()
        new_comment.entity_id = entity_id
        new_comment.comment = comment
        new_comment.save()
        entity.comment += 1
        entity.save()

    return HttpResponseRedirect(reverse('detail', args=(entity_id, )))
def recoverpasswordconfirm(request):
    recover_ver(request, False, True)
    process_access(request, 'secretcode')

    actualcode = request.session['secretcode']
    secretcode = request.POST['secretcode']
    if actualcode != secretcode:
        context = {'error_message': 'Incorrect code! Recovery failed'}
        return render(request, 'account/login.html', context)

    new_password = request.POST['password']
    confirm_password = request.POST['confirmpassword']
    if new_password != confirm_password:
        context = {
            'error_message': 'Different password given! Recovery failed'
        }
        return render(request, 'account/login.html', context)

    ac = Account.objects.get(id=request.session['recover_id'])
    ac.password = new_password
    ac.save()

    #logout of recover_id
    try:
        del request.session['recover_id']
    except KeyError:
        pass
    try:
        del request.session['secretcode']
    except KeyError:
        pass
    context = {'error_message': 'Password saved'}
    return render(request, 'account/login.html', context)
def createprocess(request):
    process_access(request, 'yourname')

    types = ['Student', 'Tourist', 'Businessman']

    yourname = request.POST['yourname']
    user_name = request.POST['username']
    password = request.POST['password']
    confirmpw = request.POST['confirm_password']
    phoneno = request.POST['phone_number']
    email = request.POST['email']
    address = request.POST['address']
    try:
        typeno = request.POST['actype']
    except MultiValueDictKeyError:
        return render(request, 'account/createac.html',
                      {'error_message': "Please choose your account type."})
    else:
        type = types[int(typeno) - 1]

    for ac in Account.objects.all():
        if ac.username == user_name:
            return render(request, 'account/createac.html',
                          {'error_message': "This username have been chosen."})
        if ac.email_address == email:
            return render(
                request, 'account/createac.html',
                {'error_message': "This email have been registered."})

    if password != confirmpw:
        return render(request, 'account/createac.html',
                      {'error_message': "Your password does not match."})

    newac = Account(name=yourname,
                    account_type=type,
                    username=user_name,
                    password=password,
                    phone_number=phoneno,
                    email_address=email,
                    residential_address=address)

    newac.save()

    subject = 'Welcome to Smart City!'
    from_email = settings.DEFAULT_FROM_EMAIL
    message = ''
    recipient_list = [newac.email_address]
    html_message = '<h3>' + 'Hello, ' + newac.username + '<br><br>Here is a warm welcome from SmartCity, feel free to browse the website and enjoy your time! ' + '<br><br>Smart City</h3>'

    send_mail(subject,
              message,
              from_email,
              recipient_list,
              fail_silently=False,
              html_message=html_message)

    return HttpResponseRedirect(reverse('login'))
def recoverusername(request):

    process_access(request, 'email')

    ac = Account.objects.filter(email_address=request.POST['email'])

    if (not ac):
        return render(request, 'account/recover_account.html',
                      {'warning': "This email does not exist"})
    request.session['recover_id'] = ac[0].id
    context = {'username': ac[0].username}
    return render(request, 'account/recover_username.html', context)
def loginver(request):
    process_access(request, 'name')

    for ac in Account.objects.all():
        if ac.username == request.POST['name']:
            acID = ac.id
            if ac.password == request.POST['password']:
                if ac.account_type == 'Admin':
                    request.session['user_id'] = ac.id
                    return HttpResponseRedirect(reverse('adminhome'))
                request.session['user_id'] = ac.id
                return HttpResponseRedirect(reverse('userhome'))

    return render(request, 'account/login.html',
                  {'error_message': "Invalid information"})
def edit_entity_save(request, entity_id):
    user_ver(request, True)
    process_access(request, 'name')

    types = [
        'College', 'Library', 'Industry', 'Hotel', 'Park', 'Zoo', 'Museum',
        'Restaurant', 'Mall'
    ]
    user_ver(request, True)
    all_en = Entity.objects.all()

    if int(entity_id) == 0:
        a = Entity()
    else:
        a = Entity.objects.get(id=entity_id)

    requestname = request.POST['name']
    for en in all_en:
        if (requestname == en.name) and int(entity_id) == 0:
            return render(request, 'entity/edit_create_entity.html', {
                'message': "An entity with this name existed.",
                'entityid': 0
            })

    try:
        typeno = request.POST['entype']
    except MultiValueDictKeyError:
        return render(request, 'entity/edit_create_entity.html',
                      {'error_message': "Please choose an entity type."})
    else:
        entype = types[int(typeno) - 1]

    a.name = requestname
    a.description = request.POST['description']
    a.address = request.POST['address']
    a.photolink = request.POST['photolink']
    a.officallink = request.POST['officallink']
    a.type = entype

    a.save()

    if int(entity_id) == 0:
        return HttpResponseRedirect(reverse('adminentitylist', args=()))
    else:
        return HttpResponseRedirect(reverse('editentity', args=(entity_id, )))
def help_message(request):
    user_ver(request, False)
    process_access(request, 'help box')

    receiving_admin = Account.objects.get(username='******')
    help_message = request.POST['help box']
    help_message = help_message.strip()

    if not help_message:
        return HttpResponseRedirect(reverse('support'))

    a = Message(senderid=request.session['user_id'],
                receiverid=receiving_admin.id,
                message=help_message)
    a.save()

    context = {}
    return HttpResponseRedirect(
        reverse('userconversation', args=(receiving_admin.id, )))
def add_message(request, receiver_id):
    user_ver(request, False, True)
    process_access(request, 'conversationbox')

    my_message = request.POST['conversationbox']
    my_message = my_message.strip()

    if my_message != "":
        a = Message(senderid=request.session['user_id'],
                    receiverid=receiver_id,
                    message=my_message)
        a.save()

    if Account.objects.get(
            id=request.session['user_id']).account_type == "Admin":
        return HttpResponseRedirect(
            reverse('adminconversation', args=(receiver_id, )))
    else:
        return HttpResponseRedirect(
            reverse('userconversation', args=(receiver_id, )))
def createadminprocess(request):
    user_ver(request, True)
    process_access(request, 'yourname')

    yourname = request.POST['yourname']
    username = request.POST['username']
    password = request.POST['password']
    confirmpw = request.POST['confirm_password']
    phoneno = request.POST['phone_number']
    email = request.POST['email']
    address = request.POST['address']

    for ac in Account.objects.all():
        if ac.username == username:
            return render(request, 'account/createac.html', {
                'error_message': "This username have been chosen.",
                'admin': True
            })
        if ac.email_address == email:
            return render(
                request, 'account/createac.html',
                {'error_message': "This email have been registered."})

    if password != confirmpw:
        return render(request, 'account/createac.html', {
            'error_message': "Your password does not match.",
            'admin': True
        })

    newac = Account(name=yourname,
                    account_type='Admin',
                    username=username,
                    password=password,
                    phone_number=phoneno,
                    email_address=email,
                    residential_address=address)

    newac.save()

    return HttpResponseRedirect(reverse('adminhome'))
def editacsave(request):
    user_ver(request, False)
    process_access(request, 'yourname')

    all_ac = Account.objects.all()
    user_ac = Account.objects.get(id=request.session['user_id'])

    acname = request.POST['yourname']
    acusername = request.POST['Username']
    acemail = request.POST['emailaddress']
    error = "Edit successful"

    for ac in all_ac:
        if acusername != user_ac.username and ac.username == acusername:
            error = "This username have been chosen."
        if acemail != user_ac.email_address and ac.email_address == acemail:
            error = "This email have been registered."

    old_pw = request.POST['old_password']
    new_pw = request.POST['new_password']
    confirm_pw = request.POST['confirm_password']

    if (new_pw or old_pw or confirm_pw):
        if (user_ac.password == old_pw and new_pw == confirm_pw):
            user_ac.password = new_pw
        else:
            error = "Invalid password"

    if error == "Edit successful":
        user_ac.name = acname
        user_ac.username = acusername
        user_ac.email_address = acemail
        user_ac.residential_address = request.POST['address']
        user_ac.phone_number = request.POST['contactnumber']
        user_ac.save()

    context = {'ac': user_ac, 'message': error}
    return render(request, 'account/edit_account_details.html', context)