"""
This script cancels all production test orders listed in the orders.csv file.

To generate the test orders csv:
1. Copy this query
SELECT O.ORDERS_ID
FROM ORDERS AS O
JOIN RESTAURANT AS R ON O.RESTAURANT_ID=R.RESTAURANT_ID
WHERE O.RESTAURANT_ID IN (13431,60770,62717,64551,65158,68675,69681,71015,73779,82552,84989,85423,85425,85433,85436,85533,85534,85535,85536,86124,87761,87782,88630,89090,89091,89205,89206,89420,91295,91541,91650,91660,89093,89096,89097,89095,90461,92019,2637124,2637125,2637126,2637127,2637128,2637129,2637130,2637131,2637132,2637133,93653,100081,93698,100547,109715)
AND (O.ORDER_CONFIRMED = 'Y' OR O.ORDER_CONFIRMED is NULL)
AND O.ORDERS_ID > 30900000

2.  Go to admin > tech > query tools
    Enter the query and run it
    Change the report settings to generate a csv, then rerun the query.
    Download the generated csv file.
  
3.  If there is already a orders.csv file in the scripts folder, delete it. 
    Then drag the dwnloaded csv file into the qascripts folder.

4. Rename the file to orders.csv

5. Run this script
"""


import os
import glob
import csv
import requests
import json

folder_path = os.path.dirname(os.path.realpath(__file__))


def main():
    print('Please ensure that the proper .csv file is located in the scripts/csvs.')
    answer = input("continue? (y/N): ").lower().strip()
    if answer == 'y' or answer == 'Y':
        cancel_orders()
    else:
        print('exiting...')


def cancel_orders():
    orders_csv_path = os.path.join(f"{folder_path}\csvs", 'orders.csv')
    try:
        with open(orders_csv_path, newline='') as orders_csv:
            orders = csv.reader(orders_csv)
            next(orders)  # skip the header row
            for order in orders:
                order_id = order[0]
                send_cancel_request(order_id)
    except FileNotFoundError:
        print('Could not open the orders.csv file. Make sure that the file exists and located in the proper directory.')


def send_cancel_request(order_id):
    url = 'https://admin.delivery.com/api/confirm/process.php'
    body = {'order_id': order_id, 'status': 'cancel'}
    headers = {'content-type': 'application/json'}
    try:
        response = requests.post(url, data=json.dumps(body), headers=headers)
        response.raise_for_status()
        print(f'order #{order_id} has been successfully canceled.')
    except (requests.ConnectionError, requests.Timeout):
        raise()
    except Exception as err:
        print(f'could not cancel order #{order_id}', err)


if __name__ == '__main__':
    main()
