# coding=utf-8

from django.core.management import BaseCommand
from django.db import IntegrityError, transaction
from django.utils import timezone

from api.models import *


class Command(BaseCommand):
    """convert free service as activity."""

    def handle(self, *args, **options):
        free_services = Service.objects.filter(payment_type=PAYMENT_TYPE.FREE_PAYMENT)

        # for every free service, create an activity
        for fs in free_services:
            print 'handling free service: %s' % fs.id

            order_count = Order.objects.filter(service_id=fs.id).count()

            end_time = timezone.now()
            start_time = fs.start_time
            if start_time > end_time:
                start_time = end_time

            with transaction.atomic():
                activity = Activity(
                    title=fs.short_description,
                    banner=fs.image_detail,
                    description=fs.detail_description,
                    points=fs.exchange_points_ceiling,
                    start_time=start_time,
                    end_time=end_time,
                    is_online=False,
                    show_win_list=False,
                    show_topics=False,
                    participants=order_count
                )
                activity.save()

                fs.is_online = False
                fs.save()
