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

import http.client

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

from mtp.apps.sync.models import *

from tendo import singleton

from ...models import *


class Command(BaseCommand):
    args = ''
    help = "Check for update server down. Not launch on global server, only on local."

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

        if settings.INSTANCE_IS_MASTER:
            return

        ups = Update.objects.filter(healthy=True).count()

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

        json = response.read()
        count = int(json)
        print("local: %s" % (ups))
        print("global: %s" % (count))
        if count > ups:
            return

        raise CommandError("No need for update")
