from django.shortcuts import render, redirect
from django.views.generic import CreateView, ListView, UpdateView, DeleteView, TemplateView
from django.contrib.auth.views import LoginView, LogoutView

from .models import Pref, Category
from .forms import SearchForm, SignUpForm, LoginForm
from django.contrib.auth import login, authenticate
import json
import requests
import environ

env = environ.Env()
env.read_env('.env')
GURUNABI_ACCESS_KEY=env('DJANGO_GURUNABI_ACCESS_KEY')
DJANGO_YAHOO_MAP_API_KEY=env('DJANGO_YAHOO_MAP_API_KEY')

def get_keyid():
    return GURUNABI_ACCESS_KEY

class IndexView(TemplateView):
    template_name = 'tabelogapp/index.html'

    def get_context_data(self, *args, **kwargs):
        searchform = SearchForm()
        params = {
            'searchform': searchform,
            }
        return params


def Search(request):
    if request.method == 'GET':
        searchform = SearchForm(request.POST)

        if searchform.is_valid():
            category_l = request.GET['category_l']
            pref = request.GET['pref']
            freeword = request.GET['freeword']
            query = get_gnavi_data("", category_l, pref, freeword, 10)
            res_list = rest_search(query)
            total_hit_count = len(res_list)
            # 4. 整形した情報をリスト形式で保存し、paramsの一要素として渡す
            restaurants_info = extract_restaurant_info(res_list)

    params = {
        'total_hit_count': total_hit_count,
        'restaurants_info': restaurants_info,
        }

    return render (request, 'tabelogapp/search.html', params)

def ShopInfo(request, restid):
    keyid = get_keyid()
    id = restid
    query = get_gnavi_data(id, "", "", "", 1)
    res_list = rest_search(query)
    restaurants_info = extract_restaurant_info(res_list)

    params = {
        'title': '店舗詳細',
        'restaurants_info': restaurants_info,
        'map_api_key': DJANGO_YAHOO_MAP_API_KEY
        }

    return render (request, 'tabelogapp/shop_info.html', params)

class SignUp(CreateView):
    form_class = SignUpForm
    template_name = 'tabelogapp/signup.html'

    def post(self, request, *args, **kwargs):
        form = self.form_class(data=request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('tabelogapp:index')
        return render(request, 'tabelogapp/signup.html', {'form': form})

class Login(LoginView):
    form_class = LoginForm
    template_name = 'tabelogapp/login.html'

class Logout(LogoutView):
    template_name = 'tabelogapp/logout.html'




def get_gnavi_data(id, category_l, pref, freeword, hit_per_page):
    keyid = get_keyid()
    # 一度に取得できる最大件数
    hit_per_page = hit_per_page
    # 店舗のid（グルナビ内で一意になっている）
    id = id
    # 大業態カテゴリ
    category_l = category_l
    #pref
    pref = pref
    #Freeword
    freeword = freeword
    #今回は関東地方のみ（コール回数を少なくするため）
    area = "AREA110"
    #パラメータ設定
    query = {"keyid": keyid, "id":id, "area":area, "pref":pref, "category_l":category_l,"hit_per_page":hit_per_page, "freeword":freeword}

    return query


def rest_search(query):
    res_list = []
    res = json.loads(requests.get("https://api.gnavi.co.jp/RestSearchAPI/v3/", params=query).text)
    # レスポンスがerror でない場合に処理を開始する
    if "error" not in res:
        res_list.extend(res["rest"])
    return res_list


def extract_restaurant_info(restaurants: 'restaurant response') -> 'restaurant list':
    restaurant_list = []
    for restaurant in restaurants:
        id = restaurant["id"]
        name = restaurant["name"]
        name_kana = restaurant["name_kana"]
        url = restaurant["url"]
        url_mobile = restaurant["url_mobile"]
        shop_image1 = restaurant["image_url"]["shop_image1"]
        shop_image2 = restaurant["image_url"]["shop_image2"]
        address = restaurant["address"]
        tel = restaurant["tel"]
        station_line = restaurant["access"]["line"]
        station = restaurant["access"]["station"]
        latitude = restaurant["latitude"]
        longitude = restaurant["longitude"]
        pr_long = restaurant["pr"]["pr_long"]

        restaurant_list.append([id, name, name_kana, url, url_mobile, shop_image1, shop_image2, address, tel, station_line, station, latitude, longitude, pr_long])
    return restaurant_list
