# -*- coding: utf-8 -*-
"""
Definition of views.
"""

from django.shortcuts import render
from django.http import HttpRequest
from django.template import RequestContext
from django.http import HttpResponse
from datetime import datetime
import ujson 
import requests
import pandas
from pandas.io.json import json_normalize
# Function GetFormular
from app.scripts.GetFormular import GetFormular

# Function GetFace
def GetFace(host, api, api_key, surname, uid = 0, firstname = '0', middlename = '0'):
    url = ''.join([str(host), str(api), 'api_key=', str(api_key)]) 
    response = requests.get(url)
    response.encoding = 'utf-8' 
    data = response.json()
    if uid == '':
        uid = 0
    else:
        uid = int(uid)
    if firstname == '':
        firstname = '0'
    if middlename == '':
        middlename = '0'
    surname = str(surname)
    assert isinstance(uid, int), 'EmpGUID  should be an int'
    assert isinstance(surname, str) and surname.isspace() != True, 'surname should be a non-space string'
    assert isinstance(surname, str) and surname, 'Inter the surname'
    assert isinstance(firstname, str) and firstname.isspace() != True, 'firstname should be a non-space string'
    assert isinstance(middlename, str) and middlename.isspace() != True, 'middlename should be a non-space string'
    face = [] 
    main_cond = "f['SurName'] == surname" 
    name_params = ["f['EmpGUID']", "f['FirstName']", "f['MiddleName']"] 
    params = [str(uid), str(firstname), str(middlename)] 
    conditions = []
    for i in range(len(params)):
        if params[i] != str(0): 
            conditions.append('and str({}) == "{}"'.format(name_params[i], params[i].strip()))
    other_cond = ' '.join([x for x in conditions]) 
    search = main_cond + ' ' + other_cond 
    for f in data:
        if eval(search): 
            face.append(f)
    error = 'Not found'
    df = json_normalize(face)
    data = df[['EmpGUID', 'SurName', 'FirstName',
           'MiddleName', 'BirthDay',]].sort_values(by=['SurName',
                                       'FirstName'])
    return data.to_html(index=False) if len(face) != 0 else error 

def home(request):
    """Renders the home page."""
    assert isinstance(request, HttpRequest)
    a='Search by individuals'
    if request.method == "POST":
        a=GetFace(host = 'https://sd.mephi.ru/', api = 'api/1/faces.json?', api_key = 'bai7phaxief4iecooTh:eeke',firstname = request.POST.get("firstname"), surname = request.POST.get("surname"), middlename = request.POST.get("middlename"), uid = request.POST.get("uid"))
    return render(
        request,
        'app/index.html',
        {
            'title':'Home Page',
            'year':datetime.now().year,
            'table': a,
        }
    )

def formular(request):
    assert isinstance(request, HttpRequest)
    a='Search by individuals'
    if request.method == "POST":
        a=GetFormular(host = 'https://sd.mephi.ru/', api = 'api/1/formulars.json?', api_key = 'bai7phaxief4iecooTh:eeke',firstname = request.POST.get("firstname"), surname = request.POST.get("surname"), middlename = request.POST.get("middlename"), uid = request.POST.get("uid"))
    return render(
        request,
        'app/getformular.html',
        {
            'title':'Get Formular'
        }
    )

def contact(request):
    """Renders the contact page."""
    assert isinstance(request, HttpRequest)
    return render(
        request,
        'app/contact.html',
        {
            'title':'Contact',
            'message':'Your contact page.',
            'year':datetime.now().year,
        }
    )

def about(request):
    """Renders the about page."""
    assert isinstance(request, HttpRequest)
    return render(
        request,
        'app/about.html',
        {
            'title':'About',
            'message':'Your application description page.',
            'year':datetime.now().year,
        }
    )

# Function GetFormular
def GetFormular(host, api, api_key, surname, uid = 0, firstname = '0', 
middlename = '0'):
    import json
    import requests
    url = ''.join([str(host), str(api), 'api_key=', str(api_key)])
    response = requests.get(url)
    data = response.json()
    if uid == '':
        uid = 0
    else:
        uid = int(uid)
    if firstname == '':
        firstname = '0'
    if middlename == '':
        middlename = '0'
    surname = str(surname)
    assert isinstance(uid, int), 'EmpGUID  should be an int'
    assert isinstance(surname, str) and surname.isspace() != True, 'surname should be a non-space string'
    assert isinstance(surname, str) and surname, 'Inter the surname'
    assert isinstance(firstname, str) and firstname.isspace() != True, 'firstname should be a non-space string'
    assert isinstance(middlename, str) and middlename.isspace() != True, 'middlename should be a non-space string'
    formular = []
    main_cond = "f['SurName'] == surname"
    name_params = ["f['EmpGUID']", "f['FirstName']", "f['MiddleName']"]
    params = [str(uid), str(firstname), str(middlename)]
    conditions = []
    for i in range(len(params)):
        if params[i] != str(0):
            conditions.append('and str({}) == "{}"'.format(name_params[i], 
params[i].strip()))
    other_cond = ' '.join([x for x in conditions])
    search = main_cond + ' ' + other_cond
    print(search)
    for f in data:
        if eval(search):
            formular.append(f)
    with open('formular.json', 'w') as write_file:
        json.dump(formular, write_file)
    if len(formular) == 0:
        print('Not Found')

def formular(request):
    """Renders the home page."""
    assert isinstance(request, HttpRequest)
    a='Search by individuals'
    if request.method == "POST":
        a=GetFace(host = 'https://sd.mephi.ru/', api = 
'api/1/formulars.json?', api_key = 'bai7phaxief4iecooTh:eeke',firstname = 
request.POST.get("firstname"), surname = request.POST.get("surname"), 
middlename = request.POST.get("middlename"), uid = 
request.POST.get("uid"))
    return render(
        request,
        'app/getformular.html',
        {
            'title':'Get Formular',
            'year':datetime.now().year,
            'table': a,
        }
    )
