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

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

    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 MainPage(request):
    from RoutesApp.forms import RouteForm

    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')[:4]

    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))


