# -*- coding: utf-8 -*-

import http.client
import json
import urllib.parse

from django.conf import settings
from django.core.management.base import BaseCommand

from tendo import singleton

from ...models import *


class Command(BaseCommand):
    args = ''
    help = 'Check update consistency.'

    def handle(self, *args, **options):
        me = singleton.SingleInstance()

        if settings.INSTANCE_IS_MASTER:
            return

        ups = Update.objects.filter(healthy=False)
        for up in ups:
            clientversion = ClientVersion.objects.filter(last_update=up).count()
            serverversion = ServerVersion.objects.filter(last_update=up).count()
            users = get_user_model().objects.filter(last_update=up).count()
            down = DownloadableFile.objects.filter(last_update=up).count()
            trainings = Training.objects.filter(last_update=up).count()

            localservers = LocalServer.objects.filter(last_update=up).count()
            trainingsessions = TrainingSession.objects.filter(last_update=up).count()
            documentsfiles = DocumentFile.objects.filter(last_update=up).count()
            documentscommentfiles = DocumentCommentFile.objects.filter(last_update=up).count()
            documents = Document.objects.filter(last_update=up).count()
            notes = Note.objects.filter(last_update=up).count()

            # current_session = CurrentSession.objects.filter(last_update=up).count()

            workp = WorkshopProperties.objects.filter(last_update=up).count()
            work = Workshop.objects.filter(last_update=up).count()
            works = WorkshopStep.objects.filter(last_update=up)
            workt = WorkshopText.objects.filter(workshopstep_ptr__in=works).count()
            worki = WorkshopImage.objects.filter(workshopstep_ptr__in=works).count()
            workq = WorkshopQuestion.objects.filter(workshopstep_ptr__in=works).count()
            works = works.count()
            workqa = WorkshopQuestionAnswer.objects.filter(last_update=up).count()

            params = urllib.parse.urlencode({
               'update_id': up.id,
               'clientversion': clientversion,
               'serverversion': serverversion,
               'users': users,
               'down': down,
               'trainings': trainings,
               'cfrs': cfrs,
               'localservers': localservers,
               'trainingsessions': trainingsessions,
               'documentsfiles': documentsfiles,
               'documentscommentfiles': documentscommentfiles,
               'documents': documents,
               'notes': notes,
               'workp': workp,
               'work': work,
               'works': works,
               'workt': workt,
               'worki': worki,
               'workq': workq,
               'workqa': workqa,
             })

            headers = {'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'}
            conn = http.client.HTTPConnection(settings.MASTER_INSTANCE_HOST)
            conn.request('POST', settings.UPDATE_CHECK_URL, params, headers)
            response = conn.getresponse()

            r = json.loads(response.read())
            if r['status'] == 'healthy':
                up.healthy = True
                up.save()
                # print '%s is healthy' % (up)
                continue

            print('%s is corrupt' % (up))
