#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# 2012 Nico Schottelius (nico-cinv at schottelius.org)
#
# This file is part of cinv.
#
# cinv is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cinv is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cinv. If not, see <http://www.gnu.org/licenses/>.
#
#

import argparse
import logging
import os.path
import os
import re
import json

from uncloud import UncloudException
from uncloud.hack.db import DB

log = logging.getLogger(__name__)


class MAC(object):
    def __init__(self, config):
        self.config = config
        self.no_db = self.config.arguments['no_db']
        if not self.no_db:
            self.db = DB(config, prefix="/mac")

        self.prefix = 0x420000000000
        self._number = 0 # Not set by default

    @staticmethod
    def validate_mac(mac):
        if not re.match(r'([0-9A-F]{2}[-:]){5}[0-9A-F]{2}$', mac, re.I):
            raise UncloudException("Not a valid mac address: %s" % mac)
        else:
            return True

    def last_used_index(self):
        if not self.no_db:
            value = self.db.get("last_used_index")
            if not value:
                self.db.set("last_used_index", "0")
                value = self.db.get("last_used_index")

        else:
            value = "0"

        return int(value)

    def last_used_mac(self):
        return self.int_to_mac(self.prefix + self.last_used_index())

    def to_colon_format(self):
        b = self._number.to_bytes(6, byteorder="big")
        return ':'.join(format(s, '02x') for s in b)

    def to_str_format(self):
        b = self._number.to_bytes(6, byteorder="big")
        return ''.join(format(s, '02x') for s in b)

    def create(self):
        last_number = self.last_used_index()

        if last_number == int('0xffffffff', 16):
            raise UncloudException("Exhausted all possible mac addresses - try to free some")

        next_number = last_number + 1
        self._number = self.prefix + next_number

        #next_number_string = "{:012x}".format(next_number)
        #next_mac = self.int_to_mac(next_mac_number)
        # db_entry = {}
        # db_entry['vm_uuid'] = vmuuid
        # db_entry['index'] = next_number
        # db_entry['mac_address'] = next_mac

        # should be one transaction
        # self.db.increment("last_used_index")
        # self.db.set("used/{}".format(next_mac),
        #             db_entry, as_json=True)

    def __int__(self):
        return self._number

    def __repr__(self):
        return self.to_str_format()

    def __str__(self):
        return self.to_colon_format()