# -*- 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.common import getValueFromCmdLine, CmdlineParams
from calculate.lib.utils.portage import isPkgInstalled
from calculate.lib.utils.files import readFile, readLinesFile
from calculate.install.distr import DistributiveError
import glob

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):
        """
        pulseaudio по умолчанию если доступно или вписано в /etc/asound.conf
        """
        avail = [x[0] for x in self.Get('os_audio_available')]
        if "pulseaudio" in avail:
            audio = getValueFromCmdLine(CmdlineParams.Calculate,
                                        CmdlineParams.Audio)
            if audio and audio == "alsa":
                return "alsa"
            return "pulseaudio"
        return "alsa"

    def choice(self):
        return self.Get('os_audio_available')


    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 ""


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

    def get(self):
        mapAudioConf = (('pulseaudio', 'media-sound/pulseaudio',
                         _("PulseAudio")),
                        ('alsa', None, _('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 generate_cards(self, cards):
        for card_id, card_name in cards:
            for playback_info in glob.glob(
                            "/proc/asound/card%s/pcm[0-9]p/info" % card_id):
                dInfo = (x.partition(":")[::2]
                         for x in readLinesFile(playback_info))
                dInfo = {x.strip(): y.strip() for x, y in dInfo}
                if all(x in dInfo for x in ('card', 'device', 'name')):
                    if card_name == dInfo['name']:
                        yield ("%s,%s" % (dInfo['card'], dInfo['device']),
                               "%s" % card_name)
                    else:
                        yield ("%s,%s" % (dInfo['card'], dInfo['device']),
                               "%s, %s" % (card_name, dInfo['name']))

    def get(self, hr=HumanReadable.No):
        # /proc/asound/card*/pcm*p/info
        data = readFile('/proc/asound/cards')
        cards = re.findall('^\s*(\d+).*\s-\s(.+)\n\s+\S.* at .*$',
                           data, re.M)
        if cards:
            return list(self.generate_cards(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,0' or
                        res and res != "0,0" and audio_default == '0,0' or
                    audio_default != self.Get('os_audio_current')):
            return 'on'
        return 'off'


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

    def get(self):
        asound_data = readFile('/etc/asound.conf')
        default_card_re = re.compile('defaults.ctl.card\s+(\d+)')
        entry = default_card_re.search(asound_data)
        if entry and entry.groups()[0] in self.Get('os_audio_id'):
            return "%s,0" % entry.groups()[0]
        default_card_re = re.compile(
            'pcm.!default {[^}]+card\s+(\d+)[^}]+device\s+(\d+)[^}]+}')
        entry = default_card_re.search(asound_data)
        if entry:
            entry = "%s,%s" % entry.groups()
            if entry in self.Get('os_audio_id'):
                return entry

        res = self.Select('os_audio_id', where='os_audio_name',
                          notlike='HDMI', limit=1)
        return res or '0,0'


class VariableOsAudioDefault(Variable):
    """
    Current default audio card
    """
    type = "choice"
    opt = ['--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 ""
