from health_view.models import *
from health_view.views import check_expiration_date
from datetime import datetime
from health_view.crypto_functions import *
import requests
import json


#needs logindata from admin account form Contentserver
loginname_restapi = ''
passwort_restapi = ''


def check_exp_date():
    licenses = License.objects.all()
    date_now = datetime.now()
    for lic in licenses:
        if check_expiration_date(lic):
            continue
        licenses_same_owner = License.objects.filter(justified=lic.justified, patient=lic.patient).exclude(id=lic.id)
        folderparts = lic.folder_parts.all().values_list()
        parts_to_delete = list()
        for part in folderparts:
            delete = True
            for license in licenses_same_owner:
                if not check_expiration_date(license):
                    continue
                for check_part in license.folder_parts.all().values_list():
                    if check_part == part:
                        delete = False
            if delete is True:
                parts_to_delete.append(part[2])
        if not parts_to_delete:
            lic.delete()
            continue
        new_total_key = make_encrypted_key_content_server()
        post_content = {
            'patient': lic.patient.username,
            'justified': lic.justified.username,
            'new_total_key': new_total_key,
            'old_total_key': lic.patient.folderinfo.content_key,
            'folder_parts': parts_to_delete,
        }
        lic.patient.folderinfo.content_key = new_total_key
        lic.patient.folderinfo.save()
        lic.delete()
        request = requests.post('http://192.168.192.75:8000/manage/delete/', json=post_content, auth=(loginname_restapi, passwort_restapi))




