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

import http.client
import urllib.parse
import requests

from uuid import getnode as get_mac

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

from mtp.apps.sync.models import Update


class Command(BaseCommand):
    """This command is called from the `ping.sh` script,
    Used to update the `update_count` for each `SLAVE` on the MASTER server
    """

    args = ''
    help = 'Update server down. Not launch on global server, only on local.'

    def handle(self, *args, **options):
        if settings.INSTANCE_IS_MASTER:
            return

        mac = get_mac()
        update_count = Update.objects.all().count()
        params = {
            'mac': '%d' % mac,
            'update_count': '%d' % update_count
        }
        ping_url = settings.MASTER_INSTANCE_HOST + reverse('sync:ping')

        requests.post(ping_url, params)
