#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2019
# This file is part of Shinken Enterprise, all rights reserved.

import optparse
import sys
import time
from pymongo.connection import Connection
from itertools import izip_longest

DELETE_GROUP_SIZE = 1000
PAUSE_TIME = 1


# Print iterations progress
def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'):
    if iteration > total:
        iteration = total
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
    """
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    sys.stdout.write('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix))
    sys.stdout.flush()


def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)


def delete_sla(item_uuid):
    con = Connection(opts.mongo_url)
    broker_db = con.shinken
    sla_archive = getattr(broker_db, 'sla_archive')
    _ids_to_delete = list(sla_archive.find({'uuid': item_uuid}, {'_id': True}))
    
    if opts.all and '-' not in item_uuid:
        _ids_to_delete.extend(list(sla_archive.find({'uuid': {'$regex': '^%s-' % item_uuid}}, {'_id': True})))
    
    print 'Found %s sla archive to delete.' % len(_ids_to_delete)
    if not _ids_to_delete:
        print 'No archive to delete was found'
        sys.exit(0)
    
    if not opts.force:
        confirm = raw_input("\nConfirm ? [y/N] : ")
        if not (confirm == 'y' or confirm == 'Y'):
            print '\nNothing was done'
            sys.exit(1)
    
    group_ids = grouper(_ids_to_delete, DELETE_GROUP_SIZE)
    group_ids = list(group_ids)
    
    nb_batch = len(group_ids)
    for batch_id, batch in enumerate(group_ids):
        printProgressBar(batch_id + 1, nb_batch, 'deleting SLA')
        # print '[%s] batch [%s]' % (batch_id, batch)
        batch = [i['_id'] for i in batch if i is not None]
        sla_archive.remove({'_id': {'$in': batch}})
        # print {'_id': {'$in': batch}}
        time.sleep(PAUSE_TIME)
    printProgressBar(nb_batch, nb_batch, 'deleting SLA')
    print
    print 'Deletion of item%s %s done.' % (' and its checks' if opts.all and '-' not in item_uuid else '', item_uuid)


if __name__ == '__main__':
    parser = optparse.OptionParser("%prog [OPTION]  ITEM_UUID", description='This tool deletes all SLA archive for an item')
    parser.add_option('-u', '--url', dest='mongo_url', default='localhost', help='URL of the mongo database [default : localhost]')
    parser.add_option('-s', '--size-batch', dest='size_batch', default=1000, type='int', help='The size of a batch of archive to delete [default : 1000]')
    parser.add_option('-p', '--pause-batch', dest='pause_batch', default=1.0, type='float', help='The pause in seconds between batches [default : 1s]')
    parser.add_option('-f', '--force', dest='force', action='store_true', default=False, help='Force deletion without asking for confirmation [default : False]')
    parser.add_option('-a', '--all', dest='all', action='store_true', default=False, help='If a host uuid is given checks attached to the host will also be deleted [default : False]')
    
    opts, args = parser.parse_args()
    if len(args) < 1:
        print 'Missing item uuid.'
        parser.print_help()
        exit(1)
    
    DELETE_GROUP_SIZE = opts.size_batch
    PAUSE_TIME = opts.pause_batch
    delete_sla(args[0])
