# coding=utf-8
import codecs

from django.conf import settings
from django.core.management import BaseCommand
from django.db.models.functions import Length
from api.models import Doctor

from services.custom_phone_service import ZTTH400

open = codecs.open


def add_phone_ext(ztth):
    doctors = Doctor.objects.annotate(ext_len=Length('phone_ext')).filter(ext_len=6)
    succ_log = open('/tmp/ztth400_success.log', 'w', 'utf8')
    error_log = open('/tmp/ztth400_error.log', 'w', 'utf8')

    for doctor in doctors:
        phone_ext = doctor.phone_ext
        phone = doctor.phone

        try:
            ztth.add_agent(phone_ext)
            ztth.agent_login(phone_ext, phone)
            msg = u'{0} {1} {2} {3}, {4}\n'.format(
                doctor.id, doctor.name, doctor.phone_ext, doctor.phone, 'success'
            )
            print msg
            succ_log.write(msg)
        except Exception, e:
            msg = u'{0} {1} {2} {3}, {4}\n'.format(
                doctor.id, doctor.name, doctor.phone_ext, doctor.phone, e.message
            )
            print msg
            error_log.write(msg)


class Command(BaseCommand):
    def handle(self, *args, **options):
        USER = settings.ZTTH_CONF.get('user')
        ACCOUNT = settings.ZTTH_CONF.get('account')
        PWD = settings.ZTTH_CONF.get('passwd')
        API_DOMAIN = settings.ZTTH_CONF.get('api_domain')
        ztth = ZTTH400(ACCOUNT, USER, PWD, API_DOMAIN)

        add_phone_ext(ztth)
