#!/usr/bin/env python

import socket
import sys
import settings


if not socket.gethostname().startswith('man') and not settings.env_type == 'production':
    sys.stderr.write('removing of deleted data cancelled')
    sys.exit(0)


import logging
from common.models import Job
from django.contrib.auth.models import User
from social_django.models import UserSocialAuth
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = 'Remove deleted jobs and users'
    logging.error('Remove deleted data is running')

    def handle(self, *args, **kwargs):
        for job in Job.objects.filter(is_deleted=True):
            logging.info('Delete job number %s', job.n)
            job.delete()
        for user in User.objects.filter(is_active=False):
            query = 'Select sa.id from social_auth_usersocialauth as sa inner join auth_user as au on sa.user_id = au.id and au.id = \'{}\''.format(user.id)
            for social in UserSocialAuth.objects.raw(query):
                logging.info('Delete social auth for user %s', social.user.email)
                social.delete()
            logging.info('Delete user %s', user.username)
            user.delete()
