import json

import arrow

from service_app_test.bases import RequestToApi
from service_app_test.api_configs import LocalAPI, BothAPIS
from service_app_test.test_application.evyos.decision_book import (
    run_decision_book_depends,
    list_decision_books,
)
from service_app_test.test_application.evyos.decision_book_items import (
    send_invitation_to_building_residents,
    collect_invitation_to_building_residents,
    assign_people_to_pre_or_wrt,
    run_decision_book_items,
)
from service_app_test.test_application.migrate_old_data.get_occupants_codes import (
    get_occupants_types,
)
from service_app_test.test_application.migrate_old_data.get_type_codes import (
    get_type_codes_key_and_class,
)
from service_app_test.test_application.migrate_old_data.people import migrate_people
from service_app_test.test_application.migrate_old_data.building import (
    migrate_build,
    migrate_build_living_space,
)
from service_app_test.test_application.migrate_old_data.company import migrate_company
from service_app_test.test_application.migrate_old_data.accounts import (
    migrate_account_records,
)
from service_app_test.test_application.migrate_old_data.decision_book_project import (
    approve_build_decision_book_project_approval,
    update_decision_book_project,
    create_decision_book_project_items,
    generate_insert_project_item,
    generate_update_project_item,
    generate_approval_project_item,
    list_decision_book_project,
)

local_api = RequestToApi()
local_api.overwrite_base_url(base_url=LocalAPI.base_url)

both_apis = BothAPIS()
both_apis.local_api = local_api


def decode_as_json_indent(data):
    return json.dumps(json.loads(json.dumps(data)), indent=2)


password_token = "Z1HtH66KFhctC02vwLshQoRC4ezo0wabZV38UAtsCD-pYobuJY_e9soTfrxNtIbCg4vXRnHgRyha44IDHNd6pmjsq1S0EM4EA5PTLBa0juHOGTs2zbs81CR_kul0kzm1pIhs8OfxrjjCQY6oDrgBxycz7HSd7M9mdvoPWNAHjaVnCAduQcuAfFNoV3p22NhW"
password_token_occ = ""
login_data = {
    "domain": "evyos.com.tr",
    "access_key": "karatay.berkay.sup@evyos.com.tr",
    "password": "string",
    "remember_me": False,
    "password_token": password_token,
}
login_creds_occupant = {
    "domain": "evyos.com.tr",
    "access_key": "mehmet.karatay@hotmail.com",
    "password": "string",
    "remember_me": False,
    "password_token": password_token_occ,
}
selection_list = [
    "73811313-7c5c-422a-bb39-08c107911799",
    "d5237a0d-1d5f-4939-93a1-a65e419b3313",
]

manager_token = "g0Z1YYjh2WqFfoI3MdJ9wrfXAHeL6f7UatEkySzOK0dFX6CH1sXgjQ"
people_uu_id = "2c8781f6-c1bc-432d-bb0c-9f5247ecc750"
list_of_attendees = [
    "_Ky6UyaoatH5CZEQHZ1gdoj_7HDxSJ2DgBwq6hSXbCKR-WG8E9DPuQ",
    "KhdJF7XP6ni_qdIRXSByGHKez8oTSbmzOAZxdi2A_iy-oOW6-VbfPA",
    "vn01wNh5moTiNzw2qOvT4h5eqgCQ10jmN3OK659NN-ekriFSmVju_Q",
    "EMsteygK4Myingptlpi_sr7Xu0Wsrl7xpQD-ukVY4GBjv6NJakpQ4Q",
    "26p4QD1CofK6-Pk_VyDOB2Xstdv_sx88kh4kResWg4TuCuAy7tAT-A",
    "2FgntLgLfFM20d32-gOwaHu44Vk_fDlpOh8IvS8gahiW-V0Dv0qLWg",
    "TwC_dNuT6Iln0NFinEuvxbnjmb_HwcS8qWg-097gjc8pHTQ1p0nTGA",
    "Yn35HP9TJonn9PTFpsq1lH3w-x-zHjTWymBeP6v4XPcwJP_aMj8JsQ",
    "C2DbYn1jcocKwjQ8gvJ_jCU0IGAmbJB3JgHj-N_OTu1jNtmhVrW7aQ",
    "TT5-9a_JVSf_WBAcN1sAfUyV45J2e7J1NoVGe3BcrrlAI1GNoU2_rw",
    "ED4H5zpmxpLXX5rO6eoTb7wIa2x1v0YbNwsFh-iAohWh7fDyhvq_BQ",
]
constant = "Toplantı sonucunda araştırmalar tamamlandı, katılımcılara e-posta gönderildi. Onaylayan sayısı yeterli olmadığı için karar alınamadı ve proje iptal edildi ve sonlandırıldı."

assign_people_to_create_item = 0
if assign_people_to_create_item == -1:
    local_api.selected_object = local_api.login_via_email_and_password(
        login_data=login_data, is_password_valid=False
    )
    migrate_company(requester=both_apis)
    migrate_people(requester=both_apis)
    migrate_build(requester=both_apis)
    migrate_build_living_space(requester=both_apis)
    # migrate_account_records(requester=both_apis)
if assign_people_to_create_item == 0:

    if not bool(selection_list):
        local_api.selected_object = local_api.login_via_email_and_password(
            login_data=login_data, is_password_valid=True
        )
        occupant_manager = get_occupants_types(
            occupant_code="BU-MNG", requester=both_apis.local_api
        )["data"]["uu_id"]

        response = both_apis.local_api.post(
            endpoint="/building/parts/list",
            data={"query": {"part_code": "MAN-ROOM"}},
        )
        print("text", response.text)
        print("json", response.json())
        response_json = response.json()
        build_parts_uu_id = response_json["data"][0]["uu_id"]

        response = both_apis.local_api.post(
            endpoint="/user/list",
            data={"query": {"email": "mehmet.karatay@hotmail.com"}},
        )
        print("text", response.text)
        print("json", response.json())
        response_json = response.json()
        person_uu_id = response_json["data"][0]["person_uu_id"]

        response = local_api.post(
            endpoint="/building/living_space/create",
            data=dict(
                build_parts_uu_id=build_parts_uu_id,
                person_uu_id=person_uu_id,
                occupant_type_uu_id=occupant_manager,
                expiry_starts=arrow.now().date().__str__(),
            ),
        )
        print("response", response.text)

    local_api.selected_object = local_api.login_via_email_and_password(
        login_data=login_creds_occupant,
        is_password_valid=bool(selection_list),
        selection_list=selection_list,
    )
    selected_decision_book_uu_id = run_decision_book_depends(
        requester=both_apis.local_api
    )
    send_invitation = {
        "build_decision_book_uu_id": selected_decision_book_uu_id,
        "message": "Request for a Regular Building Meeting",
        "planned_date": arrow.now().shift(days=2).date().__str__(),
    }
    send_invitation_to_building_residents(
        send_invitation_dict=send_invitation, requester=both_apis.local_api
    )
elif assign_people_to_create_item == 1:
    local_api.selected_object = local_api.login_via_email_and_password(
        login_data=login_creds_occupant,
        is_password_valid=True,
        selection_list=selection_list,
    )
    count = 7
    list_of_attendees.insert(0, manager_token)
    collect_invitation_to_building_residents(
        attended_dict_list=list_of_attendees,
        attend_count=count + 1,
        requester=both_apis.local_api,
    )
elif assign_people_to_create_item == 2:
    local_api.selected_object = local_api.login_via_email_and_password(
        login_data=login_creds_occupant,
        is_password_valid=True,
        selection_list=selection_list,
    )
    assign_people_to_pre_or_wrt(
        person_uu_id=people_uu_id,
        manager_token=manager_token,
        occupant_code="MT-VPR",
        requester=both_apis.local_api,
    )
    assign_people_to_pre_or_wrt(
        person_uu_id=people_uu_id,
        manager_token=manager_token,
        occupant_code="MT-WRT",
        requester=both_apis.local_api,
    )
    assign_people_to_pre_or_wrt(
        person_uu_id=people_uu_id,
        manager_token=manager_token,
        occupant_code="MT-PRS",
        requester=both_apis.local_api,
    )
elif assign_people_to_create_item == 3:
    local_api.selected_object = local_api.login_via_email_and_password(
        login_data=login_creds_occupant,
        is_password_valid=True,
        selection_list=selection_list,
    )

    selected_decision_book_uu_id = list_decision_books(requester=both_apis.local_api)[
        "data"
    ][0]["uu_id"]
    print("select_company_uu_id", local_api.selected_object)
    is_fixed_price = False

    start_date, end_date = "2024-11-01", "2024-12-01"

    info_type_reno_uu_id = get_type_codes_key_and_class(
        class_name="BuildDuesTypes", key_name="BDT-R", requester=both_apis.local_api
    )["data"]["uu_id"]
    info_type_deb_uu_id = get_type_codes_key_and_class(
        class_name="BuildDuesTypes", key_name="BDT-D", requester=both_apis.local_api
    )["data"]["uu_id"]
    info_type_inf_uu_id = get_type_codes_key_and_class(
        class_name="BuildDuesTypes", key_name="BDT-I", requester=both_apis.local_api
    )["data"]["uu_id"]

    run_decision_book_items(
        writers_token=manager_token,
        info_type_uu_id=info_type_reno_uu_id,
        item_comment="En son toplantıda bahsedilen 2 nolu daireyi etkiliyen çözüm için kanalizasyon ve "
        "tamirleri için fiyat alınarak arka alan yağmur suyu direnajının yaplımasının projelendirilmesi.",
        start_date=start_date,
        end_date=end_date,
        requester=both_apis.local_api,
    )

    unit_price = 17.04
    run_decision_book_items(
        writers_token=manager_token,
        info_type_uu_id=info_type_deb_uu_id,
        item_comment="Aidat gündemi için 1,2,3 nolu daireler için 1400 TL, diğer daireler için 1500 TL "
        "olmasına karar verildi.",
        unit_price=unit_price,
        requester=both_apis.local_api,
    )

    run_decision_book_items(
        writers_token=manager_token,
        info_type_uu_id=info_type_reno_uu_id,
        item_comment="Hali hazırda yöneticilik görevini ifa eden 4 nolu daire sahibi Mehmet Karatayın bu "
        "görevinin devam etmesine ve apartmanın bank hesaplarının kullanımı ile ilgili yetkisinin devam etmesine.",
        start_date=start_date,
        end_date=end_date,
        requester=both_apis.local_api,
    )

    run_decision_book_items(
        writers_token=manager_token,
        info_type_uu_id=info_type_reno_uu_id,
        item_comment="Kiriş içinden geçen borunun çıkarılmadan kesilmesine, gerekli tadilatın yapılıp problemin "
        "çözülmesine ayrıca bu aşamada yaplımasına onay verilirse her daire kendi radyatölerinin temizliği ve tadilatın yapılmasına.",
        start_date=start_date,
        end_date=end_date,
        requester=both_apis.local_api,
    )

    run_decision_book_items(
        writers_token=manager_token,
        info_type_uu_id=info_type_reno_uu_id,
        item_comment="Dogalgazdan tadilatında çıkan eski boruların satışının yapılmasına.",
        start_date=start_date,
        end_date=end_date,
        requester=both_apis.local_api,
    )

    run_decision_book_items(
        writers_token=manager_token,
        info_type_uu_id=info_type_reno_uu_id,
        item_comment="Apartman içinin tadilat yapılması, ışık ve elektrik sisteminin elden geçirilmesine ve elektrik "
        "sayaç il panoların kutuya konulmasına, doğalgaz borularının astar boya ile "
        "boyanmasına teklif alınarak projec açılması.",
        start_date=start_date,
        end_date=end_date,
        requester=both_apis.local_api,
    )

    run_decision_book_items(
        writers_token=manager_token,
        info_type_uu_id=info_type_reno_uu_id,
        item_comment="İç kapı teklif alınarak gerektiğinde tadilatın geliştirilmesi, tek kapı yapılması "
        "yada iki kapının alternatifi ile değerlendirilerek fiyat alınması.",
        start_date=start_date,
        end_date=end_date,
        requester=both_apis.local_api,
    )

    run_decision_book_items(
        writers_token=manager_token,
        info_type_uu_id=info_type_reno_uu_id,
        item_comment="Bina su deposunun temizletilmesi.",
        start_date=start_date,
        end_date=end_date,
        requester=both_apis.local_api,
    )

    run_decision_book_items(
        writers_token=manager_token,
        info_type_uu_id=info_type_reno_uu_id,
        item_comment="Çatının havalandırma camlarının değiştirilmesi ve onarılması.",
        start_date=start_date,
        end_date=end_date,
        requester=both_apis.local_api,
    )

    run_decision_book_items(
        writers_token=manager_token,
        info_type_uu_id=info_type_inf_uu_id,
        item_comment="Arka zemin daire sahibinin yoğun yağmurlarda evin su basmaması için "
        "arka bölüme saçak yapabilmesine onay verildi.",
        requester=both_apis.local_api,
    )
elif assign_people_to_create_item == 4:

    local_api.selected_object = local_api.login_via_email_and_password(
        login_data=login_creds_occupant,
        is_password_valid=True,
        selection_list=selection_list,
    )
    # for i in range(8):
    #     index = i + 1
    #     print("index", index)
    #     if index in [1, 7, 8]:
    #         continue
    #     project_no = f"BDT-R_2024_{index}"
    #     project = list_decision_book_project(
    #         requester=both_apis.local_api, project_no=project_no
    #     )
    #     print("project", decode_as_json_indent(project))
    #     project_uu_id = project["uu_id"]
    #
    #     insert_project_item = generate_insert_project_item(
    #         **{
    #             "build_decision_book_project_uu_id": project_uu_id,
    #             "item_header": "Toplantı sonrası alınan kararlar",
    #             "item_comment": constant,
    #         }
    #     )
    #     create_decision_book_project_items(
    #         insert_project_item=insert_project_item, requester=both_apis.local_api
    #     )
    #     approve_project_item = {
    #         "build_decision_book_project_uu_id": project_uu_id,
    #         "project_stop_date": "2024-12-01",
    #         "status_code": 9
    #     }
    #     approve_build_decision_book_project_approval(
    #         approval_project_item=generate_approval_project_item(**approve_project_item),
    #         requester=both_apis.local_api,
    #     )
    #
    #     project = list_decision_book_project(
    #         requester=both_apis.local_api, project_no=project_no
    #     )
    #     print("project", decode_as_json_indent(project))

    project_no = f"BDT-R_2024_7"
    project = list_decision_book_project(
        requester=both_apis.local_api, project_no=project_no
    )
    print("project", decode_as_json_indent(project))
    project_uu_id = project["uu_id"]

    approve_project_item = lambda final_price_list: {
        "build_decision_book_project_uu_id": project_uu_id,
        "project_stop_date": "2024-12-01",
        "final_price_list": final_price_list,
        "status_code": 9,
    }
    approve_project_dict = approve_project_item(
        [{"date": "2024-11-03", "price": 585.00}]
    )
    insert_project_item = generate_insert_project_item(
        **{
            "build_decision_book_project_uu_id": project_uu_id,
            "item_header": "Toplantı sonrası alınan kararlar",
            "item_comment": "Bina çalışmaları sonucunda 7020 ₺ lik maliyet çıkmıştır.",
        }
    )
    create_decision_book_project_items(
        insert_project_item=insert_project_item, requester=both_apis.local_api
    )
    approve_build_decision_book_project_approval(
        approval_project_item=generate_approval_project_item(**approve_project_dict),
        requester=both_apis.local_api,
    )

    project = list_decision_book_project(
        requester=both_apis.local_api, project_no=project_no
    )
    print("project", decode_as_json_indent(project))

    project_no = f"BDT-R_2024_8"
    project = list_decision_book_project(
        requester=both_apis.local_api, project_no=project_no
    )
    print("project", decode_as_json_indent(project))
    project_uu_id = project["uu_id"]

    approve_project_dict = approve_project_item(
        [
            {"date": "2024-12-01", "price": 600.25},
            {"date": "2025-01-01", "price": 600.50},
        ]
    )
    insert_project_item = generate_insert_project_item(
        **{
            "build_decision_book_project_uu_id": project_uu_id,
            "item_header": "Toplantı sonrası alınan kararlar",
            "item_comment": "Bina çalışmaları sonucunda 12500 ₺ lik maliyet çıkmıştır.",
        }
    )
    create_decision_book_project_items(
        insert_project_item=insert_project_item, requester=both_apis.local_api
    )
    approve_build_decision_book_project_approval(
        approval_project_item=generate_approval_project_item(**approve_project_dict),
        requester=both_apis.local_api,
    )

    project = list_decision_book_project(
        requester=both_apis.local_api, project_no=project_no
    )
    print("project", decode_as_json_indent(project))
