import pymongo
import pandas as pd
from pydantic import BaseModel

myclient = pymongo.MongoClient("mongodb://192.168.0.220:2747/")
mydb = myclient["factory"]
mycol = mydb["status"]
mycol.find()

class Employee_details(BaseModel):

    id: str
    certificate_number: int
    business_name: str
    date: str
    result: str
    sector: str
    address: dict
# #

dblist = myclient.list_database_names()
if "factory" in dblist:
    print("The database exists.")



class Task1:

    def read_violation(self):
        agg = list(mycol.aggregate(
            [
                {
                    '$project': {
                        '_id': '$business_name',
                        'result': 'Violation Issued'
                    }
                }, {
                '$group': {
                    '_id': '$_id',
                    'heghest': {
                        '$max': '$result'
                    }
                }
            }, {
                '$sort': {
                    'highest': -1
                }
            }
            ]))
        return (agg[0])


    def read_noviolation(self):
        r = mycol.find({"result": "No Violation Issued"})
        lst = []
        for i in r:
            lst.append(i["business_name"])
        return lst








    # class Employee_details(BaseModel):
    # )
    #     id: str
    #     certificate_number: int
    #     business_name: str
    #     date: str
    #     result: str
    #     sector: str
    #     address: dict



    def Fnd(self):
        q = mycol.find({})
        if q:
            a = []
            for i in q:
                d = {'Business Name': i['business_name'], 'Date': i["date"], 'Result': i["result"]}
                a.append(d)
            a = pd.DataFrame(a)
            return (a.to_excel("incpection.xlsx", sheet_name="mySheet", index=False))
        else:
            return "no data"






    def Insert(user):
        mycol.insert_one(user.dict())
        return "Inserted"

    def check_result(business_name, record_type):
        x = business_name
        y = record_type
        cnt = mycol.count_documents({'$and':[{'business_name':x},{'result':y}]})
        return str(cnt) +" " +str( y)