# coding=utf-8
from __future__ import unicode_literals, absolute_import, print_function

from django.conf import settings
from rpc.decorators import bind, bind_context, cache_page
from rpc.tool.error_code import gen, CODES

from api.models.area import Province, Area
from rpc.tool.log_tool import logging_exception


@bind("api/areas")
@bind("api/area/list")
@cache_page(24*60*60)
def get_all_areas():
    """所有地区，省、市
    """
    result = []
    provinces = Province.objects.filter(display_in_filter=True).order_by('id')
    for province in provinces:
        cities = [city.city_data() for city in province.cities.filter(display_in_filter=True).order_by('id')]
        province_info = province.province_data()
        province_info[u'cities'] = cities
        result.append(province_info)

    return result


@bind('api/province/info')
@cache_page(60 * 60)
def get_province_info(id):
    try:
        province = Province.objects.get(pk=id)
    except Province.DoesNotExist:
        return gen(CODES.PROVINCE_DOES_NOT_EXIST)
    return province.province_data()


@bind("api/area/register_area")
@cache_page(86400)
def get_all_register_area():
    areas = [area.data() for area in Area.objects.all()]
    return {'areas': areas}


@bind('api/area/phone_code')
def phone_area_code():
    # TODO Deprecated 所有电话号码前缀的取数据都使用方法 api/area/register_area
    area_code = settings.PHONE_AREA_CODE
    return area_code
