from django.contrib.auth import models
from django.contrib.auth.models import User
from django.db.models import Q
from django.http.response import Http404, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import redirect, render
from django.template import loader
from django.urls.base import translate_url

from sinergi.sinergi.forms import ProfileUpdateForm, UserUpdateForm
from sinergi.sinergi.models import PegawaiAktif, Organisasi, Produk, Tusi

from navigator.artikel.models import Konten #Artikel
from navigator.banner.models import Slide #Banner
from navigator.ekosistem.models import Link #Banner
from navigator.faq.models import Category #FAQ


# Create your views here.
def home(request): 
    '''
    Halaman utama Sinergi DJPK
    '''
    context = {}

    # SINERGI
    list_banner = Slide.objects.filter(featured=1).all()
    context['List_Banner'] = list_banner


    # NAVIGATOR
    list_sekilas = Konten.objects.filter(id=1)
    list_regulasi = Konten.objects.filter(id=2)
    list_pembakuan = Konten.objects.filter(id=3)
    list_faq_category = Category.objects.all()
    list_banner = Slide.objects.filter(featured=1).all()
    list_ekosistem = Link.objects.filter(featured=1).order_by('id').all()

    context['segment'] = 'index'
    context['judul'] = 'Home'
    context['headline'] = 'SIKD NAVIGATOR'
    context['Konten_Sekilas'] = list_sekilas
    context['Konten_Regulasi'] = list_regulasi
    context['Konten_Pembakuan'] = list_pembakuan
    context['List_Category'] = list_faq_category
    context['List_Banner'] = list_banner
    context['List_Ekosistem'] = list_ekosistem

    html_template = loader.get_template( 'sinergi/index.html' )
    return HttpResponse(html_template.render(context, request))


@login_required(login_url="/login/")
def profil(request):  
    '''
    Menampilkan profil pengguna
    '''
    context = {}

    html_template = loader.get_template( 'sinergi/profil.html' )
    return HttpResponse(html_template.render(context, request))


@login_required(login_url="/login/")
def organisasi(request):  
    '''
    Menampilkan organisasi pengguna
    '''
    context = {}

    # Get list organisasi
    list_org = Organisasi.objects.all()

    # Check if user selected combobox
    # If not, get default user logged in
    if request.method == 'POST':
        id = request.POST.get('esl3')
        esl3, esl4, dt = getUserInfo(request, id, False)
    else:
        id = request.user.username
        esl3, esl4, dt = getUserInfo(request, id)

    data = struktur(request, esl3, esl4, dt)


    # Get filter organisasi
    id_org = Organisasi.objects.filter(esl3=esl3)[0].id
    list_tusi = Tusi.objects.filter(esl3_id=id_org)

    context = { 'esl3': esl3, 'esl4':esl4, 
                'data': data, 
                'org': list_org, 'tusi': list_tusi}

    # return render(request, 'sinergi/struktur.html', context)
    
    html_template = loader.get_template( 'sinergi/organisasi.html' )
    return HttpResponse(html_template.render(context, request))


# @login_required(login_url="/login/")
# def produk(request):  
#     '''
#     Menampilkan produk dari unit pengguna
#     '''
#     context = {}
    
#     html_template = loader.get_template( 'sinergi/produk.html' )
#     return HttpResponse(html_template.render(context, request))

    
@login_required(login_url='/login/')
def produk(request):
    produk = Produk.objects.all()
    warna = ['primary', 'info', 'success', 'warning', 'danger']

    context = {
        'produk': produk,
        'warna': warna,
    }

    return render(request, 'sinergi/produk.html', context)


@login_required(login_url="/login/")
def stakeholder(request):
    '''
    Menampilkan stakeholder dari unit pengguna
    '''
    context = {}
    
    html_template = loader.get_template( 'sinergi/stakeholder.html' )
    return HttpResponse(html_template.render(context, request))


@login_required(login_url='/login/')
def profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, instance=request.user.profile)

        if u_form.is_valid():
            u_form.save()
            p_form.save()
            # messages.success(request, f'Your Profile has been updated succesfully')
            return redirect('profile')
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)
        context = {
            'u_form': u_form,
            'p_form': p_form,
        }
    return render(request, 'sinergi/profile.html', context)


# @login_required
@login_required(login_url='/login/')
def listPegawai(request):
    q = request.GET.get('q') if request.GET.get('q') != None else ''

    pegawaiAktif = PegawaiAktif.objects.filter(
        Q(nama__icontains=q) |
        Q(esl3__icontains=q)
    )
    # pegawaiAktif = PegawaiAktif.objects.all().order_by('nama')[:10]

    context = {
        'pegawai': pegawaiAktif,
    }

    return render(request, 'sinergi/pegawai.html', context)


@login_required(login_url='/login/')
@staff_member_required
def createnewuser(request, pk):
    user = User.objects.create_user(pk, pk+'@djpk.kemenkeu.go.id', pk)
    user.last_name = pk
    user.save()

    return HttpResponse(f'Create {user} berhasil')


def getUserInfo(request, id, default=True):
    '''
    Get user info or selected eselon 3 -> limit only first row
    '''
    if default:
        data = PegawaiAktif.objects.filter(nipbaru=id)
    else:
        data = PegawaiAktif.objects.filter(esl3=id)[0:1]
       
    esl3 = data[0].esl3
    esl4 = data[0].esl4

    return esl3, esl4, data


def struktur(request, esl3, esl4, data):
    '''
    Create organisation members by unit eselon 3
    Bug: only works for structural employees
    Next: TBA
    '''
    dt_esl3 = PegawaiAktif.objects.filter(esl3=esl3).order_by('kode_eselonisasi')

    nama = list([p.nama for p in data])

    nodes = []
    for idxa, a in enumerate(dt_esl3.filter(kode_eselonisasi=3)):
        nodes.append({
            'id':str(idxa),
            'name': a.nama,
            'title': a.namajabatan,
            'img': 'https://account.kemenkeu.go.id/manage/Uploads/Thumbnails/' + str(a.nipbaru)+'.jpg'}
        )

    idk = 0     # ID Eselon 4
    idp = 10    # ID Pelaksana
    for idxb, b in enumerate(dt_esl3.filter(kode_eselonisasi=4)):
        nodes.append({
            'id':str(idk+1),
            'pid':str(idxa),
            'name': b.nama,
            'title': b.namajabatan,
            'img': 'https://account.kemenkeu.go.id/manage/Uploads/Thumbnails/' + str(b.nipbaru)+'.jpg'}
        )
        idk += 1
        for idxc, c in enumerate(dt_esl3.filter(kode_eselonisasi=5, esl4=b.esl4)):
            nodes.append({
                'id':str(idp+1),
                'pid':str(idk),
                'name': c.nama,
                'title': c.namajabatan,
                'img': 'https://account.kemenkeu.go.id/manage/Uploads/Thumbnails/' + str(c.nipbaru)+'.jpg'}
            )
            idp += 1

    import json
    data = json.dumps(nodes)

    return data
    # context = {'data': data}

    # return render(request, 'sinergi/struktur.html', context)


#################################################################
def produk_detail(request, slug=None):
    context = {}
    context['segment'] = 'index'
    context['judul'] = 'Produk'
    context['links'] = Produk.objects.all()

    link_obj = None
    if slug is not None:
        try:
            link_obj = Produk.objects.get(slug=slug)
        except Produk.DoesNotExist:
            raise Http404
        except Produk.MultipleObjectsReturned:
            article_obj = Produk.objects.filter(slug=slug).first()
        except:
            raise Http404
    context = {
        "object": link_obj,
    }

    return render(request, 'sinergi/produk_detil.html', context=context)
    
    # html_template = loader.get_template( 'sinergi/produk_detil.html' )
    # return HttpResponse(html_template.render(context, request))