def dashboard():
    try:
        number_sites = len(database.list("sites"))
    except:
        number_sites = 0
        
    try:
        number_learning_objects = len(database.list("learning_objects"))
    except:
        number_learning_objects = 0
    
    sites = database.list("sites")    
    list_names_objets_for_sites = []
    list_numbers_objets_for_sites = []
    list_colors = []
    
    try:
        for site in sites:
            objects_for_sites = database.filter_by("learning_objects", {"classification.taxon_path.source": str(site["site"]["name"])})
            if objects_for_sites:
                list_names_objets_for_sites.append(objects_for_sites[0]['classification']['taxon_path']['source'])
                list_numbers_objets_for_sites.append(len(objects_for_sites))        
        x = 0
        while x < len(list_names_objets_for_sites):
            r = lambda: random.randint(0,255)
            list_colors.append('#%02X%02X%02X' % (r(),r(),r()))
            x += 1
    except:
        list_names_objets_for_sites.append("Nenhum")
        list_numbers_objets_for_sites.append(0)
        list_colors.append('#000000')
        
    return render_template("dashboard.html", number_sites=number_sites, number_learning_objects=number_learning_objects, list_names_objets_for_sites=list_names_objets_for_sites, list_numbers_objets_for_sites=list_numbers_objets_for_sites, list_colors=list_colors)
def view_users():
    if current_user.role != "administrator":
        flash('Acesso negado!', 'danger')
        return redirect(url_for("index"))
     
    users = database.list("users")
    return render_template("view_users.html", users=users)
def search_sites():
    if current_user.role != "administrator":
        flash('Acesso não permitido a rota especificada!', 'danger')
        return redirect(url_for("index"))
    sites_database = database.list("sites")
    stackexchange = StackExchange(100, None)
    pages_sites = stackexchange.sites()
    if sites_database:
        for page in pages_sites:
            for site in page["items"]:
                site_object = Site(site)
                site_json = site_object.get_as_json()
                for site_database in sites_database:
                    if site_json["site"]["api_parameter"] == site_database["site"]["api_parameter"]:
                        #site_update = {**site_database, **site_json}
                        site_update = site_json      
                        database.update("sites", site_database, site_update)       
                        break
                if site_update == None or "":
                    database.create("sites", site_object)
                    break
    else:
        for page in pages_sites:
            for site in page["items"]:
                try:
                    site_object = Site(site)
                    database.create("sites", site_object)
                except:
                    continue
    return redirect(url_for('view_sites'))
def results_search_database():
    global cache_app_after_login
    sites = database.list("sites")
    list_foruns = []
    list_results = []
    
    #pegar as datas
    try:
        date_start = datetime.datetime.strptime(request.form.get('date_start')[:10], "%d/%m/%Y").replace(tzinfo=pytz.utc).timestamp() #para pegar somente a data
        date_end = datetime.datetime.strptime(request.form.get('date_end')[:10], "%d/%m/%Y").replace(tzinfo=pytz.utc).timestamp() #para pegar somente a data
    except:
        date_start = datetime.datetime.strptime(request.form.get('date_start')[:10], "%m/%d/%Y").replace(tzinfo=pytz.utc).timestamp() #para pegar somente a data
        date_end = datetime.datetime.strptime(request.form.get('date_end')[:10], "%m/%d/%Y").replace(tzinfo=pytz.utc).timestamp() #para pegar somente a data
    #pegar o tipo ordenação
    selected_order = request.form.get('selected-order')
    #pegar os sites
    selected_sites = request.form.getlist('selected-sites')
    #pegar o tipo da busca
    selected_type_search = request.form.getlist('selected-type-search') 
    #pegar a busca
    search = request.form.get('search')
    
    if selected_sites:
        for option in selected_sites:
            option = option.split("-")[1]
            for site in sites:
                if option == site["site"]["api_parameter"]:
                    list_foruns.append(site["site"])
                    break
    else:
        for site in sites:
            list_foruns.append(site["site"])
        
    for site in list_foruns:
        list_result_items = database.search_advanced("learning_objects", str(search), str(site["api_parameter"]), date_start, date_end, selected_order, selected_type_search[0])
        list_results.append(list_result_items)
    
    cache_user = []
    for x in range(len(cache_app_after_login)):
        if current_user.email == cache_app_after_login[x][0]:              
            cache_user = cache_app_after_login[x]
            break        
    if cache_user and cache_user[4] != None:
        cache_user[4] = list_results
        cache_user[5] = list_foruns
    else:
        cache_user.append(current_user.email)
        cache_user.append(None)
        cache_user.append(None)
        cache_user.append(None)
        cache_user.append(list_results)
        cache_user.append(list_foruns)
        cache_app_after_login.append(cache_user)

    return render_template("results_search_database.html", list_results=cache_user[4], list_foruns=cache_user[5])
def search_api():
    sites = database.list("sites")
    list_sites = []
    for site in sites:
        list_sites.append(site["site"])
        
    days_before = datetime.datetime.today()-datetime.timedelta(days=30)
    date_start = days_before.strftime("%d/%m/%Y")
    date_end = datetime.datetime.today().strftime("%d/%m/%Y")
    
    return render_template("search_api.html", sites=list_sites, date_start=date_start, date_end=date_end)
def delete_user(email):
    if current_user.role != "administrator":
        flash('Acesso negado!', 'danger')
        return redirect(url_for("index"))
    
    user_bd = database.filter_by("users", {"email": email})
    if user_bd:
        database.delete("users", user_bd[0])
        
    users = database.list("users")
    
    flash('Usuário deletado com sucesso!', 'success')
    
    return render_template("view_users.html", users=users)
def index():   
    sites = database.list("sites")
    list_sites = []
    for site in sites:
        list_sites.append(site["site"])
        
    days_before = datetime.datetime.today()-datetime.timedelta(days=30)
    date_start = days_before.strftime("%d/%m/%Y")
    date_end = datetime.datetime.today().strftime("%d/%m/%Y")
        
    learning_objects = database.sort("learning_objects", -1, 10)
    list_learning_objects = []
    for learning_object in learning_objects:
        list_learning_objects.append(learning_object)
    return render_template("index.html", sites=list_sites, learning_objects=list_learning_objects, date_start=date_start, date_end=date_end)
def remove_admin_access(email):
    if current_user.role != "administrator":
        flash('Acesso negado!', 'danger')
        return redirect(url_for("index"))

    user_bd = database.filter_by("users", {"email": email})
    if user_bd:
        user_aux = user_bd[0]
        user_aux['role'] = "standard"
        user_aux['search_limit'] = 20
        
        database.update("users", user_bd[0], user_aux)
        
        flash('Acesso como administrador removido do usuário!', 'success')
    
    flash('Ocorrreu um problema ao tentar remover o acesso como administrador do usuário !', 'danger')
    
    users = database.list("users")
    return render_template("view_users.html", users=users)
def view_learning_objects():
    learning_objects = database.list("learning_objects")
    list_learning_objects = []
    for learning_object in learning_objects:
        list_learning_objects.append(learning_object)
    return render_template("view_learning_objects.html", learning_objects=list_learning_objects)
def search_database():
    sites = database.list("sites")
    list_sites = []
    for site in sites:
        list_sites.append(site["site"])
    return render_template("search_database.html", sites=list_sites)
def results_search_api():   
    global cache_app_after_login
    if current_user.search_limit <= 0 and current_user.role != "administrator":
        flash('Limite diário de buscas na API atingido! Novas buscas na API somente a partir de amanhã!', 'danger')
        return redirect(url_for("index")) 
    stackexchange = StackExchange(PAGE_SIZE, MAX_PAGES)
    sites = database.list("sites")
    list_sites_api = []
    list_results = []
    
    #pegar as datas
    try:
        date_start = datetime.datetime.strptime(request.form.get('date_start')[:10], "%d/%m/%Y").replace(tzinfo=pytz.utc).timestamp() #para pegar somente a data
        date_end = datetime.datetime.strptime(request.form.get('date_end')[:10], "%d/%m/%Y").replace(tzinfo=pytz.utc).timestamp() #para pegar somente a data
    except:
        date_start = datetime.datetime.strptime(request.form.get('date_start')[:10], "%m/%d/%Y").replace(tzinfo=pytz.utc).timestamp() #para pegar somente a data
        date_end = datetime.datetime.strptime(request.form.get('date_end')[:10], "%m/%d/%Y").replace(tzinfo=pytz.utc).timestamp() #para pegar somente a data
    #pegar as ordenações
    selected_sort = request.form.get('selected-sort')
    selected_order = request.form.get('selected-order')
    #pegar as tags e não tags
    selected_tagged = request.form.get('selected-tagged')
    selected_nottagged = request.form.get('selected-nottagged')
    #pegar os sites
    selected_sites = request.form.getlist('selected-sites')
    #pegar seleção de somente perguntas aceitas
    accepted = request.form.get('accepted')
    #pegar o tipo da busca
    selected_type_search = request.form.getlist('selected-type-search') 
    #pegar a busca
    search = request.form.get('search')
    
    if selected_sites:
        for option in selected_sites:
            option = option.split("-")[1]
            for site in sites:
                if option == site["site"]["api_parameter"]:
                    list_sites_api.append(site["site"])
                    break
    else:
        for site in sites:
            list_sites_api.append(site["site"])
        
    for site in list_sites_api:
        list_result_items = stackexchange.search_advanced(str(search), str(site["api_parameter"]), date_start, date_end, str(selected_sort), str(selected_order), accepted, selected_tagged, selected_nottagged, str(selected_type_search[0]))
        list_results.append(list_result_items)
    
    update_results = []
    update = []
    for results, site in zip(list_results, list_sites_api):
        for result in results:
            item_db = database.filter_by('learning_objects', {"general.identifier": result["question_id"]})
            if item_db:
                update.append(1)
            else:
                update.append(0)
        update_results.append(update)
        update = []
    
    cache_user = []
    for x in range(len(cache_app_after_login)):
        if current_user.email == cache_app_after_login[x][0]:              
            cache_user = cache_app_after_login[x]
            cache_user[1] = list_results
            cache_user[2] = list_sites_api
            cache_user[3] = update_results
            cache_app_after_login[x] = cache_user
            break        
    if not cache_user:        
        cache_user.append(current_user.email)
        cache_user.append(list_results)
        cache_user.append(list_sites_api)
        cache_user.append(update_results)
        cache_app_after_login.append(cache_user)
     
    #controle do limite de pesquisas diárias na API
    if(current_user.role == "standard"):
        current_user.search_limit -= 1
        database.update("users", database.filter_by('users', {"email": current_user.email})[0], current_user.get_as_json())
    
    
    return render_template("results_search_api.html", list_results=cache_user[1], list_sites_api=cache_user[2], update_results=cache_user[3])
def view_sites():
    sites = database.list("sites")
    list_sites = []
    for site in sites:
        list_sites.append(site["site"])
    return render_template("view_sites.html", sites=list_sites)