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

# Copyright 2015 Calculate Ltd. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import sys
from os import path
from calculate.lib.utils.files import isMount
from calculate.lib.utils.tools import Locker, LockError
from calculate.lib.cl_lang import (setLocalTranslate, getLazyLocalTranslate, _)
from .datavars import builder_data
import hashlib
import random

setLocalTranslate('cl_builder3', sys.modules[__name__])
__ = getLazyLocalTranslate(_)


class DriveSpool(object):
    """
    Объект содержит спул устройств на которые можно устанавливать систему
    """
    spool_data = path.join('/run/calculate/drives_lock')

    def __init__(self, devices, shuf=True):
        self.devices = devices
        if shuf:
            random.shuffle(self.devices)
        self.devices = iter(self.devices)
        self.lockers = []

    @staticmethod
    def device_id(device_name):
        return device_name.replace('/', "_").lstrip("_")

    @staticmethod
    def check_device(device):
        if device.startswith("/dev"):
            return path.exists(device)
        return True

    def lock_device(self, device):
        if self.check_device(device) and not isMount(device):
            device_hashfn = path.join(self.spool_data, self.device_id(device))
            locker = Locker(fn=device_hashfn, timeout=0)
            try:
                locker.acquire()
                self.lockers.append(locker)
                return True
            except LockError as e:
                return False

    def get(self):
        for device in self.devices:
            if self.lock_device(device):
                return device
        return None

    def close(self):
        for locker in self.lockers:
            locker.remove()
        self.lockers = []
