#!/usr/bin/python
# coding=utf-8

from PyQt4.QtCore import SIGNAL, pyqtSlot
import os
from ui_qss.screenResolutionSetQss import ScreenResolutionSetQss
from common import common_run


class ScreenResolutionSet(ScreenResolutionSetQss):
    def __init__(self):
        super(ScreenResolutionSet, self).__init__()
        try:
            # print self.__getScreenResolutionlist()
            common_run.CURRENT_SCREENRES = self.__getCurScreenResolution()
            self.__ScreenResolutionShow()
            self.connect(self.verticalSlider, SIGNAL("valueChanged(int)"), self.__changeResolution)
        except Exception as e:
            print e.message


    def set_pre_screen_resolution(self):
        try:
            cmd = "xrandr -s  %s" % common_run.CURRENT_SCREENRES
            # changed by pbc on 2016.05.25 for changed screenR -top
            retu = os.system(cmd)
            if retu == 0:
                __value = common_run.CURRENT_SCREENRES
                from common import screen_r
                screen_r.set_ini_value("screen", __value)
                self.emit(SIGNAL("screen_change"))
                # changed by pbc on 2016.05.25 for changed screenR -end
        except Exception as e:
            print e.message

    def setScreenResolution(self):
        try:
            value = self.verticalSlider.value()
            ###################################################################
            #add by wangshigang for no change resolution situation
            # if (self.__screenResolution[value] == common_run.CURRENT_SCREENRES):
            #     return
            ###################################################################
            cmd = "xrandr -s  %s" % self.__screenResolution[value]
            # changed by pbc on 2016.05.25 for changed screenR -top
            print "cmd:", cmd
            retu = os.system(cmd)
            if retu == 0:
                __value = self.__screenResolution[value]
                from common import screen_r
                screen_r.set_ini_value("screen", __value)
                self.emit(SIGNAL("screen_change"))

                # changed by pbc on 2016.05.25 for changed screenR -end
        except Exception as e:
            print e.message
        # finally:
        #     print "+++++++ end ++++++\n\n"

    @pyqtSlot()
    def __changeResolution(self, value):
        try:
            self.label_curResolution.setText(self.__screenResolution[value])  # 获取当前分辨率
        except Exception as e:
            print e.message

    def __ScreenResolutionShow(self):
        #self.__screenResolution = self.__getScreenResolutionlist()
        self.__screenResolution = self.__getScreenResolutionlist2()

        i = len(self.__screenResolution)
        self.verticalSlider.setMaximum(i - 1)  # 设置滑块的格子
        self.label_curResolution_max.setText(self.__screenResolution[-1])  # 显示支持最小分辨率
        self.label_curResolution_mid.setText(self.__screenResolution[i / 2])
        self.label_curResolution_min.setText(self.__screenResolution[0])  # 显示支持最大分辨率

        curResolution = self.__getCurScreenResolution()
        self.label_curResolution.setText(curResolution)  # 获取当前分辨率

        if curResolution in self.__screenResolution:
            index = self.__screenResolution.index(curResolution)
            print index
            self.verticalSlider.setValue(index)  # 设置 verticalSlider 显示当前值

        else:
            print "not find"

    # 获取当前分辨率
    def __getCurScreenResolution(self):
        cmd = "xrandr | grep \"^  .*x.*\*\" | sed  \"s/^\ \ \ //g\" | sed \"s/\ .*$//\""
        try:
            f = os.popen(cmd, "r")
            Resolution = f.readline().strip('\n')  # 去掉\n
            f.close()

        except Exception:
            raise Exception("getScreenResolution err")
        return Resolution

    # 获取终端所支持分辨率列表
    def __getScreenResolutionlist(self):
        screenResolution = []
        # "xrandr | grep "^  .*x" | sed  "s/^\ \ \ //g" | sed "s/\ .*$//""
        cmd = "xrandr | grep \"^  .*x\" | sed  \"s/^\ \ \ //g\" | sed \"s/\ .*$//\""
        try:
            f = os.popen(cmd, "r")
            while True:
                x = f.readline().strip('\n')  # 去掉\n
                if x == "":
                    break
                screenResolution.append(x)
            f.close()
            screenResolution.reverse()
        except Exception:
            raise Exception("getScreenResolution err")

        # add by pbc on 2016.05.25 for get screen list -top
        new_screenResolution = []
        for item in screenResolution:
            item_w_h_list = str(item).split("x")
            if len(item_w_h_list) == 2:
                if int(item_w_h_list[0]) >= 800 and int(item_w_h_list[1]) >= 600:
                    new_screenResolution.append(item)

        return new_screenResolution
        # add by pbc on 2016.05.25 for get screen list -end

    def __getScreenResolutionlist2(self):
        from monitor.monitorResolution import MonitorResolution
        screenResolution = []
        try:
            monitorsinfo = MonitorResolution.getMonitorsInfo()
            screenResolution =  monitorsinfo[0]["resolutionList"]

            #  最低支持分辨率 800x600
            new_screenResolution = []
            for item in screenResolution:
                item_w_h_list = str(item).split("x")
                if len(item_w_h_list) == 2:
                    if int(item_w_h_list[0]) >= 800 and int(item_w_h_list[1]) >= 600:
                        new_screenResolution.append(item)

            return new_screenResolution

        except Exception:
            raise Exception("getScreenResolution err")
        pass
###############################
#   单元测试
##############################
if __name__ == "__main__":

    from PyQt4 import QtGui
    from os import environ

    environ["WIN_UI_IMAGES_PATH"]="../../../images3"
    app = QtGui.QApplication([])
    win = ScreenResolutionSet()
    win.show()
    app.exec_()
