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

# Copyright 2008-2016 Mir Calculate. 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
import re
from calculate.lib.datavars import (Variable, ReadonlyVariable,
                                    ReadonlyTableVariable, FieldValue,
                                    HumanReadable)
from calculate.lib.utils.portage import isPkgInstalled
from calculate.lib.utils.files import readFile
from calculate.install.distr import DistributiveError

from calculate.lib.cl_lang import setLocalTranslate, _

setLocalTranslate('cl_install3', sys.modules[__name__])


class VariableOsAudio(Variable):
    """
    Выбранная аудиосистема
    """
    type = "choice"
    opt = ['--audio']
    metavalue = "AUDIO"

    def init(self):
        self.label = _("Audio system")
        self.help = _("set the audio system")

    def get(self):
        return self.choice()[0][0]

    def set(self, value):
        return {'none': ''}.get(value, value)

    def choice(self):
        return  self.Get('os_audio_available') or [('',_('None'))]


class VariableOsAudioAvailable(Variable):
    """
    Доступные звуковые системы
    """
    type = "list"

    def get(self):
        mapAudioConf = (('pulseaudio', 'media-sound/pulseaudio',
                       _("PulseAudio")),
                      ('alsa', 'media-sound/alsa-utils', _('ALSA')))
        image = self.Get('cl_image')
        if image:
            with image as distr:
                try:
                    distrPath = image.getDirectory()
                    return map(lambda x:x[0::2],
                               filter(lambda x: not x[1] or isPkgInstalled(x[1],
                                                                           prefix=distrPath),
                                      mapAudioConf))
                except DistributiveError as e:
                    pass
        return sorted(map(lambda x:x[0::2], mapAudioConf[-1:]), key=lambda x:x[1])


class VariableOsAudioData(ReadonlyTableVariable):
    """
    Information about audio cards
    """
    source = ['os_audio_id',
              'os_audio_name']

    def get(self, hr=HumanReadable.No):
        data = readFile('/proc/asound/cards')
        cards = re.findall('^\s*(\d+).*\n\s+(\S.*) at .*$', data, re.M)
        if cards:
            return map(list, cards)
        else:
            return [[]]

    setValue = Variable.setValue


class VariableOsAudioId(FieldValue, ReadonlyVariable):
    """
    Order Id of audio card
    """
    type = "list"
    source_variable = "os_audio_data"
    column = 0


class VariableOsAudioName(FieldValue, ReadonlyVariable):
    """
    Name of audio card
    """
    type = "list"
    source_variable = "os_audio_data"
    column = 1


class VariableOsAudioDefaultSet(ReadonlyVariable):
    """
    Force write in config 0
    """
    type = "bool"

    def get(self):
        res = self.Select('os_audio_id', where='os_audio_name',
                          notlike='HDMI', limit=1)
        audio_default = self.Get('os_audio_default')
        if (audio_default != '0' or
                        res and res != "0" and audio_default == '0' or
                    audio_default != self.Get('os_audio_current')):
            return 'on'
        return 'off'


class VariableOsAudioCurrent(ReadonlyVariable):
    """
    Current default audio card
    """

    def get(self):
        default_card_re = re.compile('defaults.ctl.card\s+(\d+)')
        entry = default_card_re.search(readFile('/etc/asound.conf'))
        if entry and entry.groups()[0] in self.Get('os_audio_id'):
            return entry.groups()[0]
        res = self.Select('os_audio_id', where='os_audio_name',
                          notlike='HDMI', limit=1)
        return res or '0'


class VariableOsAudioDefault(Variable):
    """
    Current default audio card
    """
    type = "choice"
    opt = ['--audio-card']
    metavalue = "CARD"

    def init(self):
        self.label = _("Default audio card")
        self.help = _("set the default audio")

    def get(self):
        return self.Get('os_audio_current')

    def choice(self):
        data = self.Get('os_audio_data')
        if data and data[0]:
            return self.Get('os_audio_data')
        return []

    def uncompatible(self):
        """
        Audio setting up unavailable for flash installation
        """
        if self.Get('os_install_root_type') == 'flash':
            return _("Audio configuration unavailable for Flash install")
        if self.Get('os_install_alsa_set') == 'off':
            return \
                _("This distribution does not provide the ALSA sound")
        return ""
