from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect

from account.models import User, Company, Department


@login_required(login_url='/')
def setting(request):
    title = 'Setting'

    departmentList = Department.objects.all()
    company = Company.objects.get(id=1)
    return render(request, 'setting.html', {'title':title, 'company':company, 'departmentList':departmentList})

def changePassword(request):
    user = request.user
    if request.method == "POST":
        password = request.POST['password']
        change_password = request.POST['change_password']
        if user.check_password(password):
            user.set_password(change_password)
            user.save()

            user = authenticate(username=user.username, password=change_password)

            if user is not None:
                login(request, user)

                return redirect('/setting')

    return redirect('/setting')


def changeUserInfo(request):
    if request.method == "POST":
        user = User.objects.get(id=request.user.id)

        name = request.POST['user_name']
        email = request.POST['user_email']

        user.name = name
        user.email = email
        try:
            propic = request.FILES['user_propic']
            user.propic = propic

        except:
            pass

        user.save()

    return redirect('/setting')

def companyInfo(request):
    if request.method == "POST":
        company = Company.objects.get(id=1)
        try:
            companyName = request.POST['company']
            company.name = companyName
        except:
            pass

        try:
            company_code = request.POST['company_code']
            company.code = company_code
        except:
            pass

        company.save()

    return redirect('/setting')

def createDepartment(request):

    department = request.POST['department']

    Department(name=department).save()

    return redirect('/setting')