#-*- 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 re
from calculate.lib.datavars import Variable,ReadonlyVariable,VariableError
from calculate.lib.utils.files import readFile, readLinesFile, listDirectory
from calculate.lib.utils.device import lspci, getUdevDeviceInfo
from itertools import *

class VariableHrBoardModel(ReadonlyVariable):
    """
    Motherboard model
    """
    def get(self):
        modelFile = "/sys/class/dmi/id/board_name"
        return readFile(modelFile).strip()

class VariableHrBoardVendor(ReadonlyVariable):
    """
    Motherboard vendor
    """
    def get(self):
        """Get motherboard vendor"""
        vendorFile = "/sys/class/dmi/id/board_vendor"
        return readFile(vendorFile).strip()

class VariableHrCdromSet(ReadonlyVariable):
    """
    Cdrom device
    """
    type = "bool"

    def get(self):
        for cdrom in ifilter(lambda x:x.startswith('/sys/block/sr'),
                     listDirectory('/sys/block',fullPath=True)):
            if getUdevDeviceInfo(path=cdrom).get('ID_CDROM','') == "1":
                return "on"
        else:
            return "off"

class VariableHrCpuNum(ReadonlyVariable):
    """
    Processors count
    """

    def init(self):
        self.label = _("Number of processors")

    def get(self):
        cpuinfoFile = "/proc/cpuinfo"
        return str(len(filter(lambda x:x.startswith("processor"),
                       readLinesFile(cpuinfoFile))) or 1)

class VariableHrVirtual(ReadonlyVariable):
    """
    Virtual machine name (virtualbox,vmware,qemu or "")
    """

    def get(self):
        virtSysDict = {'VirtualBox':'virtualbox',
                       'VMware':'vmware',
                       'Qumranet':'qemu'}
        reVirtInfo = re.compile("|".join(virtSysDict.keys()))
        devices = lspci(reVirtInfo.search)
        for device in devices.values():
            nameRes = reVirtInfo.search(device['name'])
            if not nameRes:
                nameRes = reVirtInfo.search(device['vendor'])
            if nameRes:
                return virtSysDict[nameRes.group()]
        return ""

class VariableHrLaptop(ReadonlyVariable):
    """
    Laptop variable.

    If computer is notebook then variable contains vendor
    """

    def get(self):
        """Laptop vendor"""
        chassisType = '/sys/class/dmi/id/chassis_type'
        boardVendor = '/sys/class/dmi/id/board_vendor'
        notebookChassis = ['1','8','10']
        if readFile(chassisType).strip() in notebookChassis:
            return (readFile(boardVendor).strip().split(" ")[0]).lower() or \
                "unknown"
        return ""

class VariableHrLaptopModel(ReadonlyVariable):
    """
    Laptop model name
    """
    def get(self):
        boardName = '/sys/class/dmi/id/board_name'
        if self.Get('hr_laptop') and os.access(boardName,os.R_OK):
            valBoardName = readFile(boardName).strip()
            return valBoardName or "unknown"
        return ""

class VariableHrVideoName(ReadonlyVariable):
    """
    Video vendor full name
    """

    def init(self):
        self.label = _("Videocard")

    def get(self):
        pciVideo = list(sorted(lspci("VGA compatible").items()))
        if pciVideo:
            pciVideo = pciVideo[0][1]
            vendor=pciVideo.get("vendor","").split(" ")[0]
            name=pciVideo.get("name","")
            if "[" in name and "]" in name:
                name = name.partition("[")[2].partition("]")[0]
            return "{vendor} {name}".format(vendor=vendor,name=name)
        return ""

class VariableHrVideo(ReadonlyVariable):
    """
    Videocard vendor shortname (ati,nvidia,intel,via,vmware or other)
    """

    def get(self):
        """Videocard vendor"""
        line = self.Get('hr_video_name').lower()
        if any(x in line for x in ("nvidia","geforce")):
            return "nvidia"
        if any(x in line for x in ("ati","radeon")):
            return "ati"
        elif "intel" in line:
            return "intel"
        elif "via" in line:
            return "via"
        elif "vmware" in line:
            return "vmware"
        else:
            return "other"
