# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/integrations/Automation.ipynb.

# %% auto 0
__all__ = ['remove_partition_by_x_days']

# %% ../../nbs/integrations/Automation.ipynb 2
import csv
import datetime as DT
import os
from dataclasses import dataclass

import domolibrary.client.DomoAuth as dmda
import domolibrary.classes.DomoDataset as dmds
import domolibrary.classes.DomoInstanceConfig as dmic

import utils.Exceptions as ex

import pandas as pd


# %% ../../nbs/integrations/Automation.ipynb 3
async def remove_partition_by_x_days(auth: dmda.DomoFullAuth,
                                     dataset_id: str,
                                     x_last_days: int = 0,
                                     separator: str = None,
                                     date_index: int = 0,
                                     date_format: str = '%Y-%m-%d'):
    domo_ds = dmds.DomoDataset(auth=auth, id=dataset_id)

    list_partition = await domo_ds.list_partitions(auth=auth, dataset_id=dataset_id)

    today = DT.date.today()
    days_ago = today - DT.timedelta(days=x_last_days)
    for i in list_partition:
        compare_date = ''
        if separator is not None and separator != '':
            compare_date = i['partitionId'].split(separator)[date_index]
        else:
            compare_date = i['partitionId']

        try:
            d = DT.datetime.strptime(compare_date, date_format).date()
        except ValueError:
            d = None
        if d is not None and d < days_ago:
            print(auth.domo_instance, ': 🚀  Removing partition key : ',
                  (i['partitionId']), ' in ', dataset_id)
            await domo_ds.delete_partition(dataset_partition_id=i['partitionId'], dataset_id=dataset_id,
                                           auth=auth)

