#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function, division, unicode_literals
from itertools import repeat, chain
import time
from datetime import datetime

from slackclient import SlackClient

# Get API Tokens
from hirax_tokens import HIRAX_BOT_TOKEN

testing = False # If true output to bot_testing
sc = SlackClient(HIRAX_BOT_TOKEN)

bot_user_id = 'U89TN9CN9'
site_status_channel_id = 'C8B6TKZ8D'
bot_testing_group_id = 'G89LY2ECB'
site_status_testing_group_id = 'G89TD2H45'
site_alerts_testing_group_id = 'G89P4CZR8'

lookback_hours = 2
delete_older_than_days = 7

# Unix epoch time
oldest = int(time.time() - lookback_hours*3600) # since lookback_hours
print(datetime.utcfromtimestamp(oldest))
print(oldest)

result = sc.api_call(
    'channels.history',
    channel=site_status_channel_id,
    oldest=str(oldest),
    as_user=True,
    inclusive=True,
)

from_bot = [mes for mes in result['messages'] if mes['user'] == bot_user_id]
print(len(from_bot))
if len(from_bot) < 1:
    # Bot not checking in...
    result = sc.api_call(
        'channels.history',
        channel=site_status_channel_id,
        as_user=True,
        count=20,
    )
    from_bot = [mes for mes in result['messages'] if mes['user'] == bot_user_id]
    latest = from_bot[0]['ts']
    strlatest = str(datetime.utcfromtimestamp(float(latest)))[:-7]

    alert ='\n'.join([
        '*Alert:* No status report within previous {:.1f} hours.'.format(float(lookback_hours)),
        'Last site check-in at {:s} UTC'.format( strlatest)])

    sc.api_call(
        "chat.postMessage",
        channel='#site_alerts_testing' if testing else '#site_alerts',
        text=alert,
        as_user=True,
    )
else:
    sc.api_call(
        "chat.postMessage",
        channel='#bot_testing',
        text='Bot check-in successful',
        as_user=True,
    )

delete_latest = int(time.time() - delete_older_than_days*3600*24)

def accumulate_expired_messages(channel, latest, is_group=False):
    has_more = True
    messages = []
    while has_more:
        result = sc.api_call(
            'channels.history' if not is_group else 'groups.history',
            channel=channel,
            latest=str(latest),
            as_user=True,
            inclusive=True,
            count=1000)
        time.sleep(1.1) # Avoid rate-limit
        messages.extend(result['messages'])
        has_more = result['has_more']
    return zip(repeat(channel), messages)

# Channel, message pairs
to_delete = list(chain(
    accumulate_expired_messages(
        site_status_channel_id, delete_latest, is_group=False),
    accumulate_expired_messages(
        bot_testing_group_id, delete_latest, is_group=True)),
    accumulate_expired_messages(
        site_status_testing_group_id, delete_latest, is_group=True),
    accumulate_expired_messages(
        site_alerts_testing_group_id, delete_latest, is_group=True))
# Delete old messages
delete_count = 0
if not testing:
    for ch, mes in to_delete:
        if 'user' in mes and mes['user'] == bot_user_id:
            sc.api_call(
                'chat.delete',
                channel=ch,
                ts=mes['ts'],
                as_user=True)
            delete_count += 1
            time.sleep(1.1) # Avoid rate-limit

sc.api_call(
        'chat.postMessage',
        channel='#bot_testing',
        text='Deleted {:d} old messages'.format(delete_count),
        as_user=True)
