# -*- 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"
            else:
                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 = (
            ('alsa', None, _('ALSA')),
            ('pulseaudio', 'media-sound/pulseaudio', _("PulseAudio")),
        )
        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 VariableOsAudioCardMap(ReadonlyVariable):
    """
    Соответствие номеров звуковых карт именам
    """
    type = Variable.Types.Table

    def get(self):
        return [(cardid[17:-3], readFile(cardid).strip())
                for cardid in glob.glob('/proc/asound/card[0-9]*/id')]


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 VariableOsAudioCardDefault(Variable):
    """
    Идентификатор карты по умолчанию
    """
    def get(self):
        audio_default = self.Get('os_audio_default')
        if audio_default and audio_default != "none":
            cardmap = dict(self.Get("os_audio_card_map"))
            cardnum = audio_default.split(',')[0]
            if cardnum in cardmap:
                return cardmap[cardnum]
            return "0"
        return ""

class VariableOsAudioDeviceDefault(Variable):
    """
    Номер устройства по умолчанию
    """
    def get(self):
        audio_default = self.Get('os_audio_default')
        if audio_default and audio_default != "none":
            return self.Get('os_audio_default').split(',')[1]
        return ""


class VariableOsAudioCardNameDefault(Variable):
    """
    Название карты используемое в настройках KDE
    """
    def get(self):
        try:
            audio_default = self.Get('os_audio_default')
            if audio_default and audio_default != "none":
                cardnum = int(audio_default.split(',')[0])
                audionames = self.Get('os_audio_name')
                if cardnum < len(audionames):
                    return audionames[cardnum].split(',')[0]
        except ValueError:
            pass
        return ""


class VariableOsAudioHw(Variable):
    """
    Current default audio card
    """

    def get_deprecated(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
        return ""

    def get(self):
        cardmap = dict(self.Get("os_audio_card_map"))
        value = self.get_deprecated()
        if not value:
            value = self.Select('os_audio_id', where='os_audio_name',
                          notlike='HDMI', limit=1) or "0,0"
        cardnum, devicenum = value.split(",")
        if cardnum in cardmap:
            return "{},{}".format(cardmap[cardnum], devicenum)
        return ""

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):
        current = self.Get('os_audio_hw')
        if current and "," in current:
            cardmap = {y:x for x, y in self.Get("os_audio_card_map")}
            cardid, devicenum = current.split(",")
            if cardid in cardmap:
                return "{},{}".format(cardmap[cardid], devicenum)
        data = self.Get('os_audio_data')
        if data and data[0]:
            return "0,0"
        return "none"

    def choice(self):
        data = self.Get('os_audio_data')
        if data and data[0]:
            return self.Get('os_audio_data')
        return [("none", _("Not 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 ""
