from django.shortcuts import render, redirect, HttpResponse
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.conf import settings
from .models import Poseters

from datetime import datetime
import random
import json
import ast
import os


# Create your views here.
def index(req):
    # return redirect('dbloginadmin/index.html')
    return render(req, 'dbloginadmin/index.html')

def inacound(req):
    if req.method == 'POST':
        if req.POST.get('userrr') == '1w05h7py180p4h10g' and req.POST.get('password') == 'fos2g5i47tt90n1p':
            return render(req, 'loginedtest/index.html')
        else:
            return redirect('/adminsystemdb')
    else:
        return redirect('/adminsystemdb')




def get_random():
    n = 20
    al = "abcdefghigklmnopqrstuvwxyz"
    thing = ""
    for i in range(0, n):
        a = random.randint(0, 1)
        if a == 0:
            thing += al[random.randint(0, len(al)-1)]
        else:
            thing += str(random.randint(0, 10))
    return thing


def get_data(req):

    try:
        if not req.POST['csrfmiddlewaretoken']:
            return HttpResponse('fuk yo')
    except Exception:
        return HttpResponse('')
    

    text_res = ""

    list_res = []

    if req.POST['header']:
        text_res += f"\nзагаловок: {req.POST['header']}\n"
        list_res.append(['header', f"{req.POST['header']}"])
    
    if req.POST['text']:
        text_res += f"\nтекст: {req.POST['text']}\nзтекст\n"
        list_res.append(['text', f"{req.POST['text']}"])


    if req.FILES.getlist('imgg'):
        imgs_names = []
        for i in req.FILES.getlist('imgg'):
            fo = ""
            for j in i.name[::-1]:
                if j == ".":
                    fo += j
                    break
                fo += j
            nn = get_random() + f"{datetime.now()}".replace("-", "").replace(" ", "").replace(":", "").replace(".", "")[:-6] + fo[::-1]
            nn = nn.replace(" ", "_")
            path = default_storage.save(f"tmp/{nn}", ContentFile(i.read()))
            tmp_file = os.path.join(settings.MEDIA_ROOT, path)
            os.replace(tmp_file, tmp_file[:-len(nn)-10]+f'static/tmp/{nn}')

            imgs_names.append(nn)
        text_res += f"картинка: {imgs_names}"

        list_res.append(['img', ['tmp/'+ i for i in imgs_names] ])

    
    if len(f"{list_res}") == 2:
        data = json.dumps(
                    {'text':text_res, 
                    'list_preview':'', 
                    'postname': req.POST["postname"],
                    'authtor': req.POST["authtor"]
                    }
                    )
    else:
        data = json.dumps(
            {'text':text_res, 
            'list_preview':f"{list_res}"[1:-1]+',',
            'postname': req.POST["postname"],
            'authtor': req.POST["authtor"]
            }
            )
    

    return HttpResponse(data)

   

def clear_blog(req):

    res = ast.literal_eval(req.POST['tolist'])


    return HttpResponse(f"{res}")
    global text_imgs
    global res_text_render
    global post_name
    global authtor
    global new_res_text_render
    new_res_text_render = []
    text_imgs = []
    res_text_render = ""
    post_name = ""
    authtor = ""
    return render(req, 'loginedtest/index.html')

def blog_preview(req):
    if Poseters.objects.filter(title=req.POST['postnamee']).values():
        return HttpResponse("Статья с таким названием уже существует!")
    
    try:
        res = ast.literal_eval(req.POST['to_list'])
    except Exception:
        res = ''

    if req.FILES.getlist('imgg_preview'):
        i = req.FILES.getlist('imgg_preview')[0]
        fo = ""
        for j in i.name[::-1]:
            if j == ".":
                fo += j
                break
            fo += j
        nn = get_random() + f"{datetime.now()}".replace("-", "").replace(" ", "").replace(":", "").replace(".", "")[:-6] + fo[::-1]
        nn = nn.replace(" ", "_")
        path = default_storage.save(f"tmp/{nn}", ContentFile(i.read()))
        tmp_file = os.path.join(settings.MEDIA_ROOT, path)
        os.replace(tmp_file, tmp_file[:-len(nn)-10]+f'static/tmp/{nn}')
            
        # path = default_storage.save(f"tmp/{i.name}", ContentFile(i.read()))
        # tmp_file = os.path.join(settings.MEDIA_ROOT, path)
        # name = ""
        # for j in tmp_file[::-1]:
        #     if j == '/':
        #         break
        #     name += j
        # name = name[::-1]
        # os.replace(tmp_file, tmp_file[:-len(name)-10]+f'adminsystemdb/static/tmp/{name}')
        img_preview = 'tmp/' + nn
        
    else:
        img_preview = ''
    
    return render(req, "preview_api/index.html", {"namee":"preview",

                                                "title":req.POST['postnamee'],
                                                "testthing":res,
                                                "authtor":req.POST["authtorr"],
                                                "papka":req.POST["papka"],
                                                "desc":req.POST["desc"],
                                                "img_preview": img_preview,
                                                })

    
    


def blog_preview2(req):
    try:
        res = ast.literal_eval(req.POST['testthing'])
    except Exception:
        res = ''
    return render(req, 'blog_preview/index.html',{'title':req.POST['title'],
                                                  "testthing":res,
                                                  "authtor":req.POST["authtor"],
                                                  "date":f" {datetime.today()}"[:-10],
                                                  "papka":req.POST["papka"],
                                                  "desc":req.POST["desc"],
                                                  "img_preview": req.POST['img_preview']
                                                  })

def post_to_db(req):
    src = req.POST

    
    papka = src["papka"]
    title = src["title"]
    authtor = src["authtor"]
    date = src["date"]
    testthing = src["testthing"]
    desc = src["desc"]
    img_preview = src["img_preview"]
    Poseters.objects.create(papka=papka, title=title, authror=authtor, date=date, content=testthing, desc=desc, img_preview=img_preview)

    return redirect(f"/{papka}?type={papka}&title={title}")
