# coding=utf-8

import re
import json

from celery import shared_task
from django.conf import settings
from gm_types.gaia import DOCTOR_TYPE

from api.models import Hospital, Doctor, ItemWiki
from gaia.routers import thread_local
from rpc.cache import search_dic_cache
from search.utils.dic import HospitalNameParser, DoctorNameParser, WikiNameParser, DIC_CACHE_KEY


@shared_task
@thread_local(DB_FOR_READ_OVERRIDE=settings.SLAVE_DB_NAME)
def calc_search_dic():
    hospital_name_parser = HospitalNameParser()
    hospital_name_terms = set()
    doctor_name_parser = DoctorNameParser()
    doctor_name_terms = set()
    wiki_name_parser = WikiNameParser()
    wiki_name_terms = set()

    hospitals = Hospital.objects.all()
    for hospital in hospitals:
        terms = hospital_name_parser.parse(hospital.name)
        hospital_name_terms.update(terms)

    doctors = Doctor.objects.filter(is_online=True)
    for doctor in doctors:
        if doctor.doctor_type == DOCTOR_TYPE.DOCTOR:
            terms = doctor_name_parser.parse(doctor.name)
        else:
            terms = hospital_name_parser.parse(doctor.name)
        doctor_name_terms.update(terms)

    wikis = ItemWiki.objects.filter(is_online=True)
    synonym_re = re.compile(r'[，、]')
    for wiki in wikis:
        terms = wiki_name_parser.parse(wiki.item_name)
        synonym_list = re.split(synonym_re, wiki.synonym)
        for s in synonym_list:
            terms += wiki_name_parser.parse(s)
        wiki_name_terms.update(terms)

    d = {
        'doctor_dict': list(doctor_name_terms),
        'hospital_dict': list(hospital_name_terms),
        'wiki_dict': list(wiki_name_terms),
    }
    search_dic_cache.set(DIC_CACHE_KEY, json.dumps(d))
