# coding=utf-8
from __future__ import print_function, unicode_literals, absolute_import


from django.core.management.base import BaseCommand, CommandError
from talos.models.topic import Problem
from talos.models.diary import Diary
from talos.views.topic.data_sync import get_topics, get_topics_gql
from api.models.diary import Diary as DiaryOld
from api.models.topic import Problem as ProblemOld
import random
import copy
import json
import time


class Command(BaseCommand):
    RAND_CNT = 100  # may get RAND_CNT or RAND_CNT+1 pks

    def add_arguments(self, parser):
        parser.add_argument('--topic-id', dest='topic_ids', metavar='TOPIC_ID', type=int, nargs='*')
        #parser.add_argument('--diary-id', dest='diary_ids', metavar='DIARY_ID', type=int, nargs='*')

    def rand_pks(self, model):
        total_cnt = model.objects.count()
        step = total_cnt / self.RAND_CNT
        base = random.randint(0, step-1)
        res = []
        for i in range(base, total_cnt, step):
            x = model.objects.order_by('id')[i:i+1]
            res.append(x[0].id)
        return res

    def handle(self, *args, **kwargs):
        topic_ids = kwargs['topic_ids'] or self.rand_pks(Problem)
        self.query_old(topic_ids)
        self.query_new(topic_ids)

    def query_old(self, topic_ids):
        start_time = time.time()
        get_topics.func(topic_ids)
        end_time = time.time()
        print('old query for %d topics takes time: %fs' % (self.RAND_CNT, end_time-start_time))

    def query_new(self, topic_ids):
        start_time = time.time()
        get_topics_gql(topic_ids)
        end_time = time.time()
        print('new query for %d topics takes time: %fs' % (self.RAND_CNT, end_time-start_time))
