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

# Copyright 2020 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.cl_lang import setLocalTranslate
import calculate.lib.utils.device as device
from calculate.lib.utils.files import process, getProgPath

_ = lambda x: x
setLocalTranslate('cl_lib3', sys.modules[__name__])

def get_edid_data():
    for fn in device.sysfs.glob(device.sysfs.Path.Drm,"*/edid"):
        ediddata = device.sysfs.read(fn)
        if ediddata:
            return ediddata
    return None

class EdidInfoError(Exception):
    pass

class EdidInfo(object):
    reBaseEDID = re.compile("\nBlock \d, Base EDID:.*?\nChecksum:",
        re.S)
    reDTD = re.compile(r"DTD\s+\d+:\s*(\d+x\d+)\s+(?:[0-9.]+\s+Hz)"
        "\s+(\d+:\d+)\s+[^(]+\((\d+) mm x (\d+) mm\)")

    def __init__(self):
        self.edid_decode = getProgPath('/usr/bin/edid-decode')
        if not self.edid_decode:
            raise EdidInfoError(_("{} not found"))
        self.resolution = None
        self.ratio = None
        self.screensize = None

    def set_data(self, data):
        p = process(self.edid_decode, "-")
        p.write(data)
        if p.failed():
            raise EdidInfoError(
                _("Failed to parse EDID information: {}").format(p.readerr()))
        self.parse(p.read())

    def parse(self, edid_decode_data):
        m = self.reBaseEDID.search(edid_decode_data)
        if not m:
            raise EdidInfoError(_("Failed to get Base EDID block"))
        base_edid = m.group()
        m = self.reDTD.search(base_edid)
        if not m:
            raise EdidInfoError(_("Failed to get DTD record"))
        self.resolution, self.ratio, sizex, sizey = m.groups()
        self.screensize = "{}x{}".format(sizex, sizey)
