import os
from posixpath import join
from re import M
import pandas as pd
from api import Api


class Main:
    def __init__(self):
        self.pacientet_api = Api("pacientet")
        self.klinikat_api = Api("klinikat")
        self.shtrimet = Api("shtrimet")
        self.diagnozat = Api("diagnozat")

        pass

    def read_excel(self):
        xlsx_path = os.path.join(os.path.dirname(__file__), '../Excel/')
        for dirpath, dirname, filename in os.walk(xlsx_path):
            for name in filename:
                if name.startswith('kirurgji_') or name.startswith('OBS-GYN_') or name.startswith('urgjenca_'):
                    klinika_emer = name.replace('.xlsx', '').split('_')[0]
                    klinika_filter = f"filter=(emer='{klinika_emer}')"
                    klinika_res = self.klinikat_api.create_collection(
                        {"emer": klinika_emer}, filter=klinika_filter)
                    klinika_id = klinika_res['items'][0]['id']
                    klinika = klinika_res['items'][0]
                    df = pd.read_excel(os.path.join(dirpath, name), parse_dates=[
                                       'DATELINDJA_KORIGJ'], sheet_name='Sheet1')
                    df = pd.read_excel(os.path.join(dirpath, name), parse_dates=[
                                       'DT_SHTRIMI_KORIGJ'], sheet_name='Sheet1')
                    df.dropna(subset=['EMER'], inplace=True)
                    for index, row in df.iterrows():
                        emer = row['EMER'].strip()
                        mbiemer = row['MBIEMER'].strip()
                        mosha = row['MOSHA']
                        diagnoza = row['DIAGNOZA']
                        if pd.isnull(df.loc[index, 'DATELINDJA_KORIGJ']):
                            datelindja = ''
                        else:
                            datelindja = row['DATELINDJA_KORIGJ']

                        if pd.isnull(df.loc[index, 'DT_SHTRIMI_KORIGJ']):
                            data_e_shtrimit = ''
                        else:
                            data_e_shtrimit = row['DT_SHTRIMI_KORIGJ']
                        if pd.isnull(df.loc[index, 'ERROR']):
                            error = ''
                        else:
                            error = row['ERROR']

                        new_pacient = {"emer": emer, "mbiemer": mbiemer,
                                       "datelindja": str(datelindja), "mosha": str(mosha), "error": str(error)}
                        pacient_filter = f"filter=(emer='{emer}' %26%26 mbiemer='{mbiemer}' %26%26 datelindja='{datelindja}')"

                        pacienti_res = self.pacientet_api.create_collection(
                            new_pacient, filter=pacient_filter)
                        pacienti_id = pacienti_res['items'][0]['id']
                        pacienti = pacienti_res['items'][0]

                        new_shtrimi = {
                            "pacienti": pacienti_id, "klinika": klinika_id, "data_shtrimit": str(data_e_shtrimit)}
                        shtrimi_filter = f"filter=(pacienti='{pacienti_id}' %26%26 klinika='{klinika_id}')"

                        shtrimi_res = self.shtrimet.create_collection(
                            new_shtrimi, shtrimi_filter)
                        shtrimi_id = shtrimi_res['items'][0]['id']

                        shtrimi = shtrimi_res['items'][0]

                        new_diagnoza = {"diagnoza": diagnoza,
                                        "pacienti": pacienti_id, "shtrimi": shtrimi_id, "klinika": klinika_id}
                        diagnoza_filter = f"filter=(pacienti='{pacienti_id}' %26%26 klinika='{klinika_id}')"

                        diagnoza_res = self.diagnozat.create_collection(
                            new_diagnoza, diagnoza_filter)
                        diagnoza_id = diagnoza_res['items'][0]['id']
                        diagnoza = diagnoza_res['items'][0]
                        print('\n\n\n\n')
                        print(diagnoza_res)
                        print('\n\n\n\n')

    # def test_backend(self):
        # shtrimet_res = self.shtrimet_api.list_collection()
        # print(shtrimet_res["totalItems"])
        # pacient_filter = f"expand=klinika_id"
        # pacientet_res = self.pacientet_api.list_collection(
            # filter=pacient_filter)
        # print(pacientet_res)
        # print(pacientet_res["totalItems"])


main = Main()
# main.test_backend()
main.read_excel()
# api = Api("pacientet")
# new_pacient = {"emer": "Test", "mbiemer": "test",
#                "mosha": 100, "datelindja": datetime.now().isoformat()}
# filter = f"(emer='{new_pacient['emer']}'&&mbiemer='{new_pacient['mbiemer']}'&&datelindja={new_pacient['datelindja']})"
# pacientet = api.list_collection(filter=filter)
# if len(pacientet["items"]) > 0:
#     print('egziston')
# else:
#     print('saving')
#     res = api.create_collection(new_pacient)


# # r = requests.post('http://127.0.0.1:8090/api/collections/pacientet/records', json=json=json.dumps(new_pacient), headers=headers)
