# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
import requests
import json
import inspect
from api.models.types import DOCTOR_ORDER_TYPE, DIARY_ORDER_TYPE
from search.utils.diary import search_diary
from search.utils.doctor import search_doctor
from search.utils.topic import search_topic
from search.utils.service import search_service
from search.utils.itemwiki import search_itemwiki
from search.utils.tag import search_tag

class Command(BaseCommand):
    args = ''
    help = 'search test data dump'

    from optparse import make_option
    option_list = BaseCommand.option_list + (
        make_option('-t', '--type', dest='type', help='type name', metavar='TYPE'),
        make_option('-q', '--query', dest='query', help='query', metavar='QUERY'),
        make_option('-u', '--user-city-tag-id', dest='user_city_tag_id', type='int', help='user city tag id', metavar='USER_CITY_TAG_ID'),
        make_option('-s', '--size', dest='size', type='int', help='result size', metavar='SIZE', default=5),
        make_option('-f', '--offset', dest='offset', type='int', help='result offset', metavar='OFFSET', default=0),
        make_option('-r', '--sort-type', dest='sort_type', help='sort type', metavar='SORT_TYPE'),
        make_option('-e', '--extra-option', dest='ex_opt', help='extra options in JSON' , metavar='EXTRA_OPTION'),
    )

    def handle(self, *args, **options):
        if not options['type']:
            raise CommandError('type name must be specified')
        elif not (options['type'] in [
            'topic', # 帖子
            'tag', # 圈子
            'itemwiki', # 百科
            'diary', # 日记本
            'service', # 福利
            'doctor', # 医生
        ]):
            raise CommandError('unknown type name, type must be one of [topic, tag, itemwiki, diary, service, doctor]')
        search_funcs = {
            'topic':search_topic,
            'tag':search_tag,
            'itemwiki':search_itemwiki,
            'diary':search_diary,
            'service':search_service,
            'doctor':search_doctor,
        }

        s = search_funcs[options['type']]
        params = {
            'query': options['query'] if options['query'] else u'双眼皮',
            'size': options['size'],
            'offset': options['offset'],
        }
        s_args = inspect.getargspec(s)
        if ('sort_type' in s_args.args) and (options['sort_type']):
            # tricky
            if options['type'] in ('service', 'doctor'):
                options['sort_type'] = int(options['sort_type'])
            params['sort_type'] = options['sort_type']
        if 'user_city_tag_id' in s_args.args:
            params['user_city_tag_id'] = options['user_city_tag_id']

        if options['ex_opt']:
            ex_opt = json.loads(options['ex_opt'])
            params.update(ex_opt)

        print json.dumps(s(**params))

