import json

from django.http import HttpResponse, Http404, FileResponse
from django.template import loader, RequestContext
from django.contrib.auth.decorators import login_required
from .models import *
from django.conf import settings
from .funcs import get_inter_http_respose
from django.http.response import JsonResponse, HttpResponse
from django.views.decorators.http import require_GET, require_POST
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_exempt
from webpush import send_user_notification
import json

def test_code(request):
    from RoutesApp.funcs import get_city_by_type_transport_and_address_point
    from RoutesApp.models import Route
    from ReferenceDataApp.models import Airport, City

    # import allauth
    # from allauth.socialaccount.models import SocialApp
    # apps = SocialApp.objects.all()
    # apps.delete()

    from RoutesApp.search_matches import search_matches
    search_matches()

    # try:
    #     # body = request.body
    #     # data = json.loads(body)
    #     # if 'head' not in data or 'body' not in data or 'id' not in data:
    #     #     return JsonResponse(status=400, data={"message": "Invalid data format"})
    #     # user_id = data['id']
    #     user = request.user
    #     payload = {'head': '123', 'body': 'qwerty'}
    #     send_user_notification(user=user, payload=payload, ttl=1000)
    #     return JsonResponse(status=200, data={"message": "Web push successful"})
    # except TypeError:
    #     return JsonResponse(status=500, data={"message": "An error occurred"})

    # routes = Route.objects.all()
    #
    # for route in routes:
    #     print(route.id)
    #     required_save = False
    #     if not route.from_city:
    #         route.from_city = get_city_by_type_transport_and_address_point(route.type_transport, route.from_address_point)
    #         required_save = True
    #
    #     if not route.to_city:
    #         route.to_city = get_city_by_type_transport_and_address_point(route.type_transport,
    #                                                                             route.to_address_point)
    #         required_save = True
    #
    #     if required_save:
    #         route.save()

    return HttpResponse('finished')



def Page404(request, exeption=None):

    Dict = {}

    t = loader.get_template('404.html')
    try:
        res = get_inter_http_respose(t, Dict, request)
        return HttpResponse(res, status=404)
    except Exception as e:
        return HttpResponse(str(e))




def MainPage(request):
    from RoutesApp.forms import RouteForm

    from .init_options import init_options
    init_options()


    print(f'LOCALE_PATHS = {str(settings.LOCALE_PATHS)}')

    page = StaticPage.objects.get(url='main')

    from ArticlesApp.models import ArticleModel
    arts = ArticleModel.objects.filter(enable=True).order_by('-createDT')[:3]

    Dict = {
        'page': page,
        'FAQ': page.FAQ_items.filter(enable=True),
        'route_form': RouteForm(),
        'articles': arts,
        'owner_type': 'mover'
    }



    breadcrumbs_Dict = {
    }
    Dict.update({'breadcrumbs': breadcrumbs_Dict})

    t = loader.get_template('pages/p_main.html')
    return get_inter_http_respose(t, Dict, request)
    # return HttpResponse(t.render(Dict, request))



def StaticPageView(request, url):
    from RoutesApp.forms import RouteForm
    from SubscribesApp.funcs import get_subsribes_w_options

    Dict = {}

    if url == '':
        return MainPage(request)
    elif url  == 'for_movers':
        Dict.update({
            'route_form': RouteForm(),
            'owner_type': 'customer',
        })
    elif url == 'for_customers':
        Dict.update({
            'route_form': RouteForm(),
            'owner_type': 'mover'
        })
    # elif  url == 'works':
    #     return WorksPage(request)
    elif url in ['main']:
        raise Http404

    if url in ['for_movers', 'for_customers']:
        subscribes, all_options = get_subsribes_w_options()
        Dict.update({
            'subscribes': subscribes,
        })

    try:
        page = StaticPage.objects.get(url=url)
    except StaticPage.DoesNotExist:
        raise Http404


    Dict.update({
        'page': page,
    })

    t = loader.get_template('pages/p_static_page.html')
    return get_inter_http_respose(t, Dict, request)
    # return HttpResponse(t.render(Dict, request))


