#!/usr/bin/env python
# coding=utf-8

from django.core.management import BaseCommand

from api.models import Doctor, DoctorAgreement
from doctor.models.capture import DoctorRegisterAgreement


class Command(BaseCommand):

    def handle(self, *args, **options):
        cache_doctor_ids = {}

        def get_doctor_id(register):
            doctor_id = cache_doctor_ids.get(register.id)
            if not doctor_id:
                try:
                    doctor = Doctor.objects.get(user__person__id=register.person_id)
                    doctor_id = doctor.id
                    cache_doctor_ids[register.id] = doctor_id
                except Doctor.DoesNotExist:
                    pass
            return doctor_id

        not_handle_ids = []
        for dra in DoctorRegisterAgreement.objects.all():
            doctor_id = get_doctor_id(dra.doctor_register)
            if doctor_id:
                print u'handle register_id is %s, doctor_id is %s' % (dra.doctor_register_id, doctor_id)
                DoctorAgreement.objects.get_or_create(
                    doctor_id=doctor_id,
                    image_url=dra.image_url,
                )
            else:
                not_handle_ids.append(str(dra.doctor_register_id))

        if not_handle_ids:
            print u"don't hava doctor register_ids >> %s" % (', '.join(set(not_handle_ids)))
