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

import http.client
import urllib.parse
from uuid import getnode as get_mac

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

from tendo import singleton

from ...models import *


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

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

        if settings.INSTANCE_IS_MASTER:
            return

        mac = get_mac()
        params = urllib.parse.urlencode({'mac': "%d" % mac})
        headers = {'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'}
        conn = http.client.HTTPConnection(settings.MASTER_INSTANCE_HOST)
        conn.request('POST', settings.LOCK_UPDATE_UP_URL, params, headers)

        response = conn.getresponse()
        if response.status == 200:
            return

        raise CommandError("Unable to lock for upload")
