from django.contrib.auth import models
from django.contrib.auth.models import User
from django.core import paginator
from django.db.models import Q
from django.db.models.functions import Length
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 Jurnal, Kmanagement, PegawaiAktif, Organisasi, Produk, Tusi, OrganisasiNew, Video, Dok
from sinergi.sinergi.models import Berita

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

import requests, json
from bs4 import BeautifulSoup
from urllib.request import urlopen
from urllib.error import URLError, HTTPError

import datetime

# 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
    context['berita_feat'] = Berita.objects.filter(featured=1).order_by('-date_added')
    context['berita_norm'] = Berita.objects.filter(featured=0).order_by('-date_added')

    today = datetime.datetime.now()
    context['ultah'] = PegawaiAktif.objects.filter(tanggallahir__month=today.month, tanggallahir__day=today.day)

    id_video = 'IFR7-FxJQNM'
    video = requests.get("https://noembed.com/embed?url=https://www.youtube.com/watch?v="+id_video)
    data = video.json()
    
    context['id_video'] = 'IFR7-FxJQNM'
    context['title_video'] = data['title']

        # https://noembed.com/embed?url=https://www.youtube.com/watch?v=

    # 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()

    # BERITA
    context['segment'] = 'home'
    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
    context['layanan_sikd'] = getLayananSIKD(request)


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


def berita_grup(request):
    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

    q = request.GET.get('q') if request.GET.get('q') != None else ''

    list_berita = Berita.objects.filter(category__slug=q).order_by('-date_added')[:50]

    paginator = Paginator(list_berita, 5)
    page = request.GET.get('page', 1)

    try:
        berita = paginator.page(page)
    except PageNotAnInteger:
        berita = paginator.page(1)
    except EmptyPage:
        berita = paginator.page(paginator.num_pages)

    context = {
        'berita': berita,
    }

    context['segment'] = 'berita'

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


def berita_detil(request, slug=None):
    context = {}
    context['segment'] = 'berita'
    context['judul'] = 'Berita'
    context['links'] = Berita.objects.all()

    link_obj = None
    if slug is not None:
        try:
            link_obj = Berita.objects.get(slug=slug)
        except Berita.DoesNotExist:
            raise Http404
        except Link.MultipleObjectsReturned:
            article_obj = Berita.objects.filter(slug=slug).first()
        except:
            raise Http404
    context = {
        "object": link_obj,
    }
    context['segment'] = 'berita'

    return render(request, "sinergi/berita_detil.html", context=context)


@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 = {}

    # Memanggil data organisasi untuk combobox
    list_org, esl3, esl4, dt = comboOrganisasi(request)

    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 organisasiNew(request):  
    # context = {}

    es1 = OrganisasiNew.objects.filter(id=0)
    es2 = OrganisasiNew.objects.filter(id__gte=1).filter(id__lte=5)
    es3 = OrganisasiNew.objects.filter(id__gte=10).filter(id__lte=100)

    nodes = {}
    for i in es2:
        nodes[i.unit] = []
        for j in es3.filter(parent=i.id):
            nodes[i.unit].append(j.unit)


    esl3, list_tusi, data_str = '', '', ''
    info_unit = ''

    if request.GET.get('q'):
        unit = request.GET.get('q')
        esl3, esl4, dt = getUserInfo(request, unit, False)

        # Memanggil data organisasi untuk combobox
        # list_org, esl3, esl4, dt = comboOrganisasi(request)

        data_str = 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)
        
        id_org = OrganisasiNew.objects.filter(unit=unit)[0].id
        info_unit = OrganisasiNew.objects.filter(Q(id=id_org) | Q(parent_id=id_org))


    context = {
                'es1':es1, 'esl3': esl3, 'info_unit': info_unit,
                'data':nodes, 
                'data_str': data_str,
            }

    context['segment'] = 'menu'

    return render(request, 'sinergi/organisasi-new.html', context)


def comboOrganisasi(request):
    '''
    Membuat daftar organisasi dan menghandle combobox organisasi by eselon 3
    '''
    
     # 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)

    return list_org, esl3, esl4, dt



# @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 = {}

    # Memanggil data organisasi untuk combobox
    list_org, esl3, esl4, dt = comboOrganisasi(request)

    context = {
        'org': list_org, 'esl3': esl3, 'esl4':esl4, 
        'produk': produk,
        'warna': warna,
    }

    context['segment'] = 'menu'

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


@login_required(login_url="/login/")
def stakeholder(request):
    '''
    Menampilkan stakeholder dari unit pengguna
    '''
    data = Dok.objects.all()

    context = {
        'data': data
    }
    
    context['segment'] = 'menu'

    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,
    }

    context['segment'] = 'menu'

    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

    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))


#################################################################
@login_required(login_url="/login/")
def multimedia(request):  
    '''
    Menampilkan halaman multimedia
    '''
    video = Video.objects.all()

    context = {'video': video}
    context['segment'] = 'publikasi'

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


@login_required(login_url="/login/")
def kajian_jurnal(request):  
    '''
    Menampilkan halaman kajian dan jurnal
    '''
    context = {}

    jurnal = Jurnal.objects.all()

    context = {
        'data': jurnal
    }
    context['segment'] = 'publikasi'

    return render(request, 'sinergi/kajian-jurnal.html', context=context)


    # url = "https://djpk.kemenkeu.go.id/ejournal/arsip"  #url eJournal
    # page = urlopen(url)
    # html = page.read().decode("utf-8")
    # soup = BeautifulSoup(html, "html.parser")

    # c = soup.find(class_="tbodyArsip") # find jurnal tabel by id
    # c0 = c.find_all("tr") # Find jurnal rows
    # c0

    # title = []
    # abstract = []
    # pdf = []

    # for k in range(0, len(c0)):
    #     title.append(c0[k].find_all('label')[0].get_text()) # title
    #     abstract.append(c0[k].find_all('p')[0].get_text()) # abstract

    #     link_pdf = 'https://djpk.kemenkeu.go.id/ejournal/downloadFileArsip/'
    #     pdf.append(link_pdf + c0[k].find_all('a')[1]['data-id']) # id download PDF

    # context = {
    #     'title': title,
    #     'abstract': abstract,
    #     'pdf': pdf,
    # }


@login_required(login_url="/login/")
def knowledge_manajemen(request):  
    '''
    Menampilkan halaman kajian dan jurnal
    '''

    data = Kmanagement.objects.all()

    context = {
        'data': data
    }
    context['segment'] = 'publikasi'

    return render(request, 'sinergi/knowledge-manajemen.html', context=context)


@login_required(login_url="/login/")
def ea(request):  
    '''
    Menampilkan halaman kajian dan jurnal
    '''

    context = {}
    context['segment'] = 'ekosistem_digital'

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


@login_required(login_url="/login/")
def sdm(request):  
    '''
    Menampilkan halaman kajian dan jurnal
    '''

    context = {}
    context['segment'] = 'ekosistem_digital'

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

#########################################################################
##      LAYANAN APLIKASI - NAVIGATOR SIKD
def getLayananSIKD(request):
    url = []
    title = []
    img = []

    from urllib.error import URLError, HTTPError

    try:
        urlSIKD = "http://sikd.djpk.kemenkeu.go.id/SIKD5/public/index.sikd"
        page = urlopen(urlSIKD, timeout=1)

        html = page.read().decode("utf-8")
        soup = BeautifulSoup(html, "html.parser")

        a = soup.find_all('a')
        a = a[:-3]

        b = soup.find_all('img')
        b = b[1:-4]

        if len(a) == len(b):
            for i in range(0,len(a)):
                if a[i]['href'][1:6] == 'SIKD5':
                    url.append('http://sikd.djpk.kemenkeu.go.id/' + a[i]['href'])
                else:
                    url.append(a[i]['href'])

                title.append(a[i]['title'])
                img.append(b[i]['src'])

    except HTTPError as e: ResponseData = e.read().decode("utf8", 'ignore')
    except URLError as e: ResponseData = e.reason()
    except TimeoutError:
        url = ['#']
        title = ['Tidak terkoneksi']
        img = ['https://videohive.img.customer.envatousercontent.com/files/226167667/Connection%20Error%20590x332.jpg?auto=compress%2Cformat&fit=crop&crop=top&max-h=8000&max-w=590&s=3c8a392096a8e9131b010df745c4fbca']
    
    # context = {
    #     'link':zip(url, title, img)
    # }

    return zip(url, title, img)
