import json
import requests
import foracle
import time
import sys
import os
import logging
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta

URL = "https://app.hotellab.io/privat/api/integration/1c/set-pms-prices/5"
logpath = "log"
# lopota token
# token = "0fe53440-5425-419a-928d-b38f9b2b200e"
# library token
# token = "74c42b90-0e4e-44b9-aed5-dd3dbc000334"
# bella vista
# token = "f8186e58-8185-4643-afc3-88dd2ee3823f"
# NO token
token = "1111"
ora = foracle.oraconnect()
months = 12
path = "log"

handlers = [logging.FileHandler("hotellabpriceexport.log"), logging.StreamHandler()]
logging.basicConfig(
    handlers=handlers,
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
)

logging.info(
    "Hotellab price export module v0.1 released 23.06.2023. Made by Hatkut_Murat, http://fidelio.pro"
)

if len(sys.argv) > 1:
    months = int(sys.argv[1])
    logging.info(f"Found months number argument. Exporting {months} months")
else:
    logging.info("Months parameter has not been set. Using default value: 1 month")

if len(sys.argv) > 2:
    token = sys.argv[2]
    logging.info("Looking for security token.... ok")
else:
    logging.info("Looking for security token... FAIL! Trying with developer token")

if not os.path.exists(logpath):
    os.makedirs(logpath)

oneday = timedelta(days=1)
start_date = date.today()
end_date = start_date + relativedelta(months=+months)

while start_date <= end_date:
    edate = start_date + oneday
    q = f"select m_hlpricejson('{start_date.strftime('%d.%m.%Y')}') from dual"
    logging.info(msg=q)
    logging.info(f"Fetching prices for period {start_date.strftime('%d.%m.%Y')}")

    qr1 = ora.runquery(q)
    qr = qr1[0]

    if not qr1[0]:
        logging.error("Database SQL query error.")
        continue

    logging.info("Message with price has been created, trying to send it to Hotellab")
    res = qr.read()

    if not res:
        logging.error("Data from database is incorrect")
        continue

    timestr = time.strftime("%Y%m%d-%H%M%S")
    filename = f"{logpath}/REQ_{start_date.strftime('%Y%m%d')} - {edate.strftime('%Y%m%d')}_{time.strftime('%Y%m%d-%H%M%S')}.log"

    with open(filename, "w") as log:
        log.write(res)

    headers = {"Content-Type": "application/json", "X-HL-Token": token}
    rsp = requests.post(URL, data=res, headers=headers)

    if not rsp.ok:
        logging.error(
            f"--- Hotellab server responded with error. HTTP Status Code is { rsp.status_code }"
        )
        logging.error(rsp.text)
        continue

    jsonrsp = json.loads(rsp.content.decode())
    if not jsonrsp["success"]:
        logging.error("! - - - - - - Error sending message to Hotellab")
        continue

    filename = f"{logpath}/RSP_{start_date.strftime('%Y%m%d')} - {edate.strftime('%Y%m%d')}_{time.strftime('%Y%m%d-%H%M%S')}.log"

    with open(filename, "w") as log:
        log.write(json.dumps(jsonrsp))

    logging.info(
        f"{start_date.strftime('%Y%m%d')} Done! - - - - - - Message has been sent to Hotellab"
    )
    start_date += oneday

logging.info("- - - Finished!")
