# coding=utf-8

import datetime
import pytz

from django.conf import settings
from django.contrib.auth.models import User

from rpc.decorators import bind_context, bind, list_interface
from rpc.tool.error_code import CODES, gen

from api.models import Doctor, DoctorRegisterInfo, DOCTOR_TYPE

from doctor.models.support import JpushBindUser
from rpc.context import get_rpc_remote_invoker
from message.utils.push_service import eta_2_push_time
from api.tool.log_tool import logging_exception

TIME_ZONE = settings.TIME_ZONE


def _eta_to_duration(eta):
    eta = datetime.datetime.strptime(eta, '%Y-%m-%d %H:%M:%S')
    local_timezone = pytz.timezone(TIME_ZONE)
    local_eta = local_timezone.localize(eta)
    now = datetime.datetime.now(local_timezone)
    duration = (local_eta - now).total_seconds()
    return duration


@bind_context("doctor/support/push/one")
def push_message_one(ctx, platform, user_id, extra=None, alert='', eta=None):
    rpc_invoker = get_rpc_remote_invoker()
    try:
        rpc_invoker['push2/push/doctor/notification/uids'](
            user_ids=[user_id],
            platform=platform,
            extra=extra,
            alert=alert,
            push_time=eta_2_push_time(eta),
        ).unwrap()
    except Exception as e:
        logging_exception()


@bind_context("doctor/support/push/all")
def push_message_all(ctx, platform=None, extra=None, alert='', eta=None):
    rpc_invoker = get_rpc_remote_invoker()
    try:
        rpc_invoker['push2/push/user/notification/all'](
            platform=platform,
            alert=alert,
            extra=extra,
            push_time=eta_2_push_time(eta),
        ).unwrap()
    except Exception as e:
        logging_exception()


@bind_context("doctor/support/jpush/bind")
def jpush_bind(ctx,registration_id, user_id):
    rpc_invoker = get_rpc_remote_invoker()
    rpc_invoker['push2/bind/doctor/reg'](
        registration_id=registration_id,
        user_id=user_id,
    ).unwrap()


@bind('doctor/list')
@list_interface(offset_name='start_num', limit_name='count', element_model=Doctor, element_func_list=[Doctor.doctor_detail])
def doctor_list(start_num=0, count=10):
    docs = Doctor.objects.filter(is_online=True).exclude(hospital_id='wanmeizhensuo')
    docs = docs.filter(doctor_type=DOCTOR_TYPE.DOCTOR)
    data = []

    for d in docs[start_num:start_num+count]:
        try:
            data.append(d.doctor_detail())
        except Exception:
            pass
    return data


@bind("api/simple_doctor/list")
def get_simple_doctor_list(start_num=0, count=10):

    data = []
    doctors = Doctor.objects.filter(is_online=True, doctor_type=DOCTOR_TYPE.DOCTOR).exclude(hospital_id='wanmeizhensuo')

    for doctor in doctors[start_num:start_num+count]:
        data.append({"user": {
            "doctor_type": doctor.doctor_type,
            "name": doctor.name,
            "id": doctor.id
        }})

    return data