from django.shortcuts import render, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.files.storage import default_storage
from django.conf import settings
from django.core.files.base import ContentFile
from adminsystemdb.models import Poseters
from .models import Comments
from datetime import datetime

import random
import ast
import os

# Create your views here.
def index(req):
    ran_history = Poseters.objects.filter(papka="history").all()[:3]
    ran_places = Poseters.objects.filter(papka="places").all()[:4]
    ran_celebrity = Poseters.objects.filter(papka="celebrity").all()[:4]
    ran_theaters_and_music = Poseters.objects.filter(papka="theaters_and_music").all()[:4]
    return render(req, 'home/index.html',{
                                        "random_history":ran_history,
                                        "random_places":ran_places,
                                        "random_celebrity":ran_celebrity,
                                        "random_theaters_and_music":ran_theaters_and_music
                                        })

def render_forgk(req, defaoul, namee):
    try:
        src = req.GET
        typpee = src["type"]
        title = src["title"].replace("%20", " ")
        srcc = Poseters.objects.get(papka=typpee, title=title)

        ran_history = Poseters.objects.filter(papka="history").all()[:3]
        ran_places = Poseters.objects.filter(papka="places").all()[:4]
        ran_celebrity = Poseters.objects.filter(papka="celebrity").all()[:4]
        ran_theaters_and_music = Poseters.objects.filter(papka="theaters_and_music").all()[:4]
        return render(req, 
                      'api/index.html',
                      {"is_valid":"yes",
                       'title': srcc.title,
                       "testthing": ast.literal_eval(srcc.content),
                       "authtor": srcc.authror,
                       "date": srcc.date,
                       "papka": srcc.papka,

                       "random_history":ran_history,
                       "random_places":ran_places,
                       "random_celebrity":ran_celebrity,
                       "random_theaters_and_music":ran_theaters_and_music
                      })
    except Exception as ex:
        srcc = Poseters.objects.filter(papka=defaoul)
        ran_history = Poseters.objects.filter(papka="history").all()[:3]
        ran_places = Poseters.objects.filter(papka="places").all()[:4]
        ran_celebrity = Poseters.objects.filter(papka="celebrity").all()[:4]
        ran_theaters_and_music = Poseters.objects.filter(papka="theaters_and_music").order_by('?')[:4]
        if srcc:
            return render(req, "api/index.html", {"is_valid":"no",
                                                "namee":namee,
                                                "testthing":srcc,
                                                "random_history":ran_history,
                                                "random_places":ran_places,
                                                "random_celebrity":ran_celebrity,
                                                "random_theaters_and_music":ran_theaters_and_music
                                                })
        else:
            return render(req, "api/index.html", {"is_valid":"noo",
                                                  "namee":"ошибка...."})

def history(req, defaoul="history", namee="История"): return render_forgk(req, defaoul, namee)


def places(req, defaoul="places", namee="Места Екатеринбурга"): return render_forgk(req, defaoul, namee)


def celebrity(req, defaoul="celebrity", namee="Знаменитости"): return render_forgk(req, defaoul, namee)

def theaters_and_music(req, defaoul="theaters_and_music", namee="Театры и музыка"): return render_forgk(req, defaoul, namee)

def coments(req):
    ran_history = Poseters.objects.filter(papka="history").order_by('?')[:4]
    ran_places = Poseters.objects.filter(papka="places").order_by('?')[:4]
    ran_celebrity = Poseters.objects.filter(papka="celebrity").order_by('?')[:4]
    ran_theaters_and_music = Poseters.objects.filter(papka="theaters_and_music").order_by('?')[:4]
    return render(req, "coms/coments.html", {
                                        "random_history":ran_history,
                                        "random_places":ran_places,
                                        "random_celebrity":ran_celebrity,
                                        "random_theaters_and_music":ran_theaters_and_music
                                        })

def post_coment(req):

    Comments.objects.create(name=req.GET["name"], mail=req.GET["email"], phone_num=req.GET["phone"], coment=req.GET["message"], date_time=datetime.now())
    ran_history = Poseters.objects.filter(papka="history").order_by('?')[:4]
    ran_places = Poseters.objects.filter(papka="places").order_by('?')[:4]
    ran_celebrity = Poseters.objects.filter(papka="celebrity").order_by('?')[:4]
    ran_theaters_and_music = Poseters.objects.filter(papka="theaters_and_music").order_by('?')[:4]
    return render(req, "coms/coms_post_res.html", {"coms_name":req.GET["name"],
                                        "random_history":ran_history,
                                        "random_places":ran_places,
                                        "random_celebrity":ran_celebrity,
                                        "random_theaters_and_music":ran_theaters_and_music
                                        })

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





@csrf_exempt
def tg_test_title(req):
    try:
        if Poseters.objects.filter(title=req.GET["testtitle"]):
            return HttpResponse("bad")
        return HttpResponse("good")
    except Exception:
        return HttpResponse("hi")

@csrf_exempt
def tg_post(req):
    
    try:
        if Poseters.objects.filter(title=req.GET["testtitle"]):
            return HttpResponse("bad")
    except Exception: pass

    try:
        
        

        for i in req.FILES.getlist('imgg'):
            path = default_storage.save(f"tmp/{i.name}_{get_random()}.jpg", ContentFile(i.read()))
            tmp_file = os.path.join(settings.MEDIA_ROOT, path)

            img_name = ""
            for j in tmp_file[::-1]:
                if j == '/':
                    break
                img_name += j
            img_name = img_name[::-1]
            os.replace(tmp_file, tmp_file[:-len(img_name)-10]+f'static/tmp/{img_name}')
            break
        reqp = req.POST
        category = reqp["category"]
        title = reqp["title"]
        author = reqp["author"]
        time = reqp["time"]
        text = f"[['img', ['tmp/{img_name}']]," + reqp["text"] 
        desc = reqp["desc"]
        Poseters.objects.create(papka=category, title=title, authror=author, date=time, content=text, desc=desc, img_preview='tmp/'+img_name)
        return HttpResponse("good")
    except Exception as ex:
        return HttpResponse("hi")
    return HttpResponse("hi")

