# -*- coding: utf-8 -*-

from datetime import date

from werkzeug.exceptions import BadRequest
from flask import Blueprint, request
import requests

from schoool.renderers import render_json


view = Blueprint('auth', __name__)


@view.route('/school/search')
def search():
    query = request.values.get('query')
    if not query:
        raise BadRequest('The required parameter "query" is missing.')

    url = 'http://hes.sen.go.kr/spr_ccm_cm01_100.do'
    params = {
        'kraOrgNm': query,
    }
    json = requests.get(url, params=params).json
    dirty = json.get('resultSVO').get('orgDVOList')
    data = [{
        'code': data['orgCode'],
        'name': data['kraOrgNm'],
        'address': data['zipAdres'],
        'type': data['schulCrseScCodeNm'],
    } for data in dirty]
    return render_json(data)


@view.route('/school/<code>/meals')
def meals(code):
    year = request.values.get('year', date.today().year, type=int)
    month = request.values.get('month', date.today().month, type=int)

    url = 'http://hes.sen.go.kr/sts_sci_md00_001.do'
    data = {
        'schulCode': code,
        'schulCrseScCode': 4,
        'ay': year,
        'mm': month,
    }

    html = requests.get(url, data=data).html
    tds = [list(td.stripped_strings) for td in html.find_all('td')]
    tds = filter(None, tds)

    meals = []

    for items in tds:
        meal = {
            'date': '{}-{}-{:02d}'.format(year, month, int(items[0])),
            'lunch': [],
            'dinner': [],
        }

        try:
            dinner_index = items.index(u'[석식]')
        except ValueError:
            dinner_index = len(items) - 1

        meal['lunch'] = items[2:dinner_index]
        meal['dinner'] = items[dinner_index + 1:]
        meals.append(meal)

    return render_json(meals)

@@ -186,16 +186,488 @@
 _json%0A%0A%0A
+URLS = %5B%0A    'hes.sen.go.kr',  # %EC%84%9C%EC%9A%B8%0A    'hes.pen.go.kr',  # %EB%B6%80%EC%82%B0%0A    'hes.dge.go.kr',  # %EB%8C%80%EA%B5%AC%0A    'hes.ice.go.kr',  # %EC%9D%B8%EC%B2%9C%0A    'hes.gen.go.kr',  # %EA%B4%91%EC%A3%BC%0A    'hes.dje.go.kr',  # %EB%8C%80%EC%A0%84%0A    'hes.use.go.kr',  # %EC%9A%B8%EC%82%B0%0A    'hes.sje.go.kr',  # %EC%84%B8%EC%A2%85%0A    'hes.goe.go.kr',  # %EA%B2%BD%EA%B8%B0%0A    'hes.kwe.go.kr',  # %EA%B0%95%EC%9B%90%0A    'hes.cbe.go.kr',  # %EC%B6%A9%EB%B6%81%0A    'hes.cne.go.kr',  # %EC%B6%A9%EB%82%A8%0A    'hes.jbe.go.kr',  # %EC%A0%84%EB%B6%81%0A    'hes.jne.go.kr',  # %EC%A0%84%EB%82%A8%0A    'hes.gbe.kr',     # %EA%B2%BD%EB%B6%81%0A    'hes.gne.go.kr',  # %EA%B2%BD%EB%82%A8%0A    'hes.jje.go.kr',  # %EC%A0%9C%EC%A3%BC%0A%5D%0A%0A%0A
 view = B

Add education office urls.