import os
import sys
import time
import django
local_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
print(local_path)
if local_path not in sys.path:
    sys.path.append(local_path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kedong.settings")
django.setup()
from django.conf import settings
from smartfarming.models.device import MongoDevice, MongoCBDData
from smartfarming.models.worm_forecast import MongoCBDphoto
import json
import requests
import pymongo
from urllib import parse
from kedong.settings import MEDIA_ROOT


my_client = pymongo.MongoClient(host="8.136.98.49", port=27017, username="root", password="yfkj@6020")
my_col = my_client['smartfarming']['sa_device']

scd_device = {
"866547058627400",
"866547058637276",
"866547058633663",
"866547058613921"
}



def dsj_qxz_conf_info():
    cbd_photo = MongoCBDphoto.objects.all()
    for i in cbd_photo:
        device = MongoDevice.objects.get(id=i.device_id)
        device_id = device.device_id
        addr = "https://bigdata-image.oss-cn-hangzhou.aliyuncs.com/Basics/cbd/" + i.addr
        if i.addr == i.indentify_photo:
            cbd_path = os.path.join(MEDIA_ROOT, f"cbd/{device_id}")
            os.makedirs(cbd_path) if not os.path.exists(cbd_path) else None 
            file_name = (i.addr).split("/")[-1]
            local_addr = os.path.join(cbd_path, file_name)
            response = requests.get(addr)
            try:
                if int(response.status_code) == 200:
                    with open(local_addr, "wb") as f:
                        f.write(response.content)
            except Exception as e:
                print(e)
            tb = f"/media/cbd/{device_id}/{file_name}"
            i.addr = tb 
            i.indentify_photo = tb
            i.save()


if __name__ == "__main__":
    dsj_qxz_conf_info()
