import logging
import json

from app import app
from data.database import configure, RepositoryNotification, ExternalNotificationMethod

configure(app.config)

logger = logging.getLogger(__name__)

def run_slackwebhook_migration():
  slack_method = ExternalNotificationMethod.get(ExternalNotificationMethod.name == "slack")

  encountered = set()
  while True:
    found = list(RepositoryNotification.select().where(
                      RepositoryNotification.method == slack_method,
                      RepositoryNotification.config_json ** "%subdomain%",
                      ~(RepositoryNotification.config_json ** "%url%")))

    found = [f for f in found if not f.uuid in encountered]

    if not found:
      logger.debug('No additional records found')
      return

    logger.debug('Found %s records to be changed', len(found))
    for notification in found:
      encountered.add(notification.uuid)

      try:
        config = json.loads(notification.config_json)
      except:
        logging.error("Cannot parse config for noticification %s", notification.uuid)
        continue

      logger.debug("Checking notification %s", notification.uuid)
      if 'subdomain' in config and 'token' in config:
        subdomain = config['subdomain']
        token = config['token']
        new_url = 'https://%s.slack.com/services/hooks/incoming-webhook?token=%s' % (subdomain, token)
        config['url'] = new_url

        logger.debug("Updating notification %s to URL: %s", notification.uuid, new_url)
        notification.config_json = json.dumps(config)
        notification.save()

if __name__ == "__main__":
  logging.basicConfig(level=logging.DEBUG)
  logging.getLogger('boto').setLevel(logging.CRITICAL)

  run_slackwebhook_migration()