import pymongo
import pandas as pd
from pydantic import BaseModel, BaseModel

myclient = pymongo.MongoClient("mongodb://192.168.0.220:2747/")
mydb = myclient["bana"]

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


mycol = mydb["assignment_1"]
mycol.find()
print(mydb.list_collection_names())
class Employee_details(BaseModel):
    id: str
    certificate_number: int
    business_name: str
    date: str
    result: str
    sector: str
    address: dict
class Task1:

    def mongo(self):

        mycol = mydb["assignment_1"]
        mycol.find()
        temp=list(mycol.aggregate(
               [
                   {
                       '$project': {
                           '_id': '$business_name',
                           'result': 'Violation Issued'
                       }
                   }, {
                   '$group': {
                       '_id': '$_id',
                       'highest': {
                           '$max': '$result'
                       }
                   }
               }, {
                   '$sort': {
                       'highest': -1
                   }
               }
        ]))
        return temp[0] if temp else []

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

    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("bana.xlsx", sheet_name="mySheet", index=False))
        else:
            return "no data"
def Insert (user):
    mycol.insert_one(user.dict())
    return "inserted"