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

# Copyright 2008-2013 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 os
import sys
import re
from os import path
from calculate.lib.datavars import (Variable, VariableError, ReadonlyVariable,
                                   ReadonlyTableVariable, FieldValue)
from calculate.lib.utils.files import (readFile, getProgPath, process)

from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])

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

    def get(self,hr=False):
        alsaInfo = getProgPath('/usr/bin/alsa-info')
        if not alsaInfo:
            return [[]]
        entry = re.compile('^Card hw:(\d+)\s*[^/]+/\'(.*?) at .*$')
        return tuple(map(lambda x:x.groups(),
               filter(None,map(entry.search,
               process(alsaInfo,'--stdout',envdict=os.environ)))))

    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)
        audioDefault = self.Get('os_audio_default')
        if audioDefault != '0' or \
            res and res != "0" and audioDefault == '0' or \
            audioDefault != self.Get('os_audio_current'):
            return 'on'
        return 'off'

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

    def get(self):
        defaultCardRe = re.compile('defaults.ctl.card\s+(\d+)')
        entry = defaultCardRe.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']

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