from common.third_party_api.surveillance.ys7 import YSCloudClient

from console.video_management.models import Device

from console.video_management.models import VideoSystem

from common.third_party_api.surveillance.imou import APIClient

from common.third_party_api.danbing.openapi import ZYRHApi


def ys_cloud_device_list(**kwargs):
    devices = YSCloudClient(kwargs.get("system")).get_device_list(**{
        "pageStart": kwargs.get("pageStart"),
        "pageSize": kwargs.get("pageSize", 50),
    }).get("data")
    result = []
    device_datas = Device.objects.filter().values_list("deviceSerial", flat=True)
    for item in devices:
        if item.get("deviceSerial") in device_datas:
            continue
        result.append({
            "deviceSerial": item.get("deviceSerial"),
            "deviceName": item.get("deviceName")
        })
    return result


def imou_cloud_device_list(**kwargs):
    devices = APIClient(kwargs.get("system")).get_device_list(**{
        "pageStart": kwargs.get("pageStart"),
        "pageSize": kwargs.get("pageSize"),
    }).get("deviceList")
    result = []
    device_datas = Device.objects.filter().values_list("deviceSerial", flat=True)
    for item in devices:
        if item.get("deviceSerial") in device_datas:
            continue
        result.append({
            "deviceSerial": item.get("deviceId"),
            "deviceName": item.get("channels")[0].get("channelName") if item.get("channels") else None
        })
    return result


def ys_bind_device(**kwargs):
    devices = YSCloudClient(kwargs.get("system")).get_device_list(**{
        "pageStart": kwargs.get("pageStart"),
        "pageSize": kwargs.get("pageSize"),
    }).get("data")
    obj_list = []
    for device in devices:
        obj = Device.objects.filter(deviceSerial=device.deviceSerial, system="2").first()
        if obj:
            continue
        obj_list.append(Device(

        ))


def check_permission_of_device(**kwargs):
    device = Device.objects.filter(id=kwargs.get("id")).first()
    if not device:
        return

    if not device.system:
        return

    if device.system.account == kwargs.get("user"):
        return True


def zyrh_device_list(**kwargs):
    api = ZYRHApi(host=kwargs.get("host"), data=kwargs.get("data"))
    device_list = api.get_device_tree()
    result = []
    for item in device_list.get("list", []):
        result.append({
            "deviceSerial": item.get("code"),
            "deviceName": item.get("name")
        })
    return result
