import os
import uuid
import socket
from app.app_config import SPEAKER_CONFIG_FILE, PROJECT_CONFIG, VOLUME_CONFIG_FILE, ADDRESS_COUNT
from app import project_cf
from app import speaker_cf
from app import volume_cf

class Config(object):
    def __init__(self):
        speaker_cf.read(SPEAKER_CONFIG_FILE, encoding='utf-8')
        volume_cf.read(VOLUME_CONFIG_FILE, encoding='utf-8')
        project_cf.read(PROJECT_CONFIG, encoding='utf-8')
        #设置型号
        self.model = speaker_cf.get("system", "model")
        #系统软件版本号
        self.soft_version = speaker_cf.get("system", "firmware")
        #系统硬件版本号
        self.hard_version = speaker_cf.get("system", "hard_version")
        #系统主机名
        self.hostname = socket.getfqdn(socket.gethostname())
        #系统ip地址
        self.ipaddr = self._get_host_ip()
        #系统硬件音量
        self.hard_volume = int(volume_cf.get("volume", "volume_out"))
        #系统强控开关
        self.hard_volume_control = volume_cf.get("volume", "hard_volume_control")
        #系统分机号
        self.exten = speaker_cf.get("account_info_1", "username")
        #系统分机密码
        self.exten_password = speaker_cf.get("account_info_1", "passwd")
        #广播系统服务器地址
        self.server_ipaddr = speaker_cf.get("account_info_1", "server")
        #播放器初始化音量,播放器初始化状态,播放源

        #重启时，是否恢复播放
        self.music_auto_resume = speaker_cf.get("system", "music_auto_resume")
        if self.music_auto_resume == "yes":
            if project_cf.has_option("general", "init_player_state") and project_cf.has_option("general", "current_uri"):
                self.player_current_volume = int(volume_cf.get("volume", "broadcast_volume"))
                self.init_player_state = int(project_cf.get("general", "init_player_state"))
                self.current_uri = project_cf.get("general", "current_uri")
            else:
                if project_cf.has_section("general"):
                    volume_cf.set("volume", "broadcast_volume", "50")
                    project_cf.set("general", "init_player_state", "-1")
                    project_cf.set("general", "current_uri", "")
                else:
                    project_cf.add_section("general")
                    volume_cf.set("volume", "broadcast_volume", "50")
                    project_cf.set("general", "init_player_state", "-1")
                    project_cf.set("general", "current_uri", "")

                with open(PROJECT_CONFIG, "w") as f:
                    project_cf.write(f, space_around_delimiters=False)
                
                with open(VOLUME_CONFIG_FILE, "w") as f:
                    volume_cf.write(f, space_around_delimiters=False)
                os.system("sync")

                self.player_current_volume = int(volume_cf.get("volume", "broadcast_volume"))
                self.init_player_state = int(project_cf.get("general", "init_player_state"))
                self.current_uri = project_cf.get("general", "current_uri")
        else:
            if project_cf.has_option("general", "init_player_state") and project_cf.has_option("general", "current_uri"):
                project_cf.set("general", "init_player_state", "-1")
                project_cf.set("general", "current_uri", "")

                with open(PROJECT_CONFIG, "w") as f:
                    project_cf.write(f, space_around_delimiters=False)
                os.system("sync")

                self.player_current_volume = int(volume_cf.get("volume", "broadcast_volume"))
                self.init_player_state = int(project_cf.get("general", "init_player_state"))
                self.current_uri = project_cf.get("general", "current_uri")
            else:
                if project_cf.has_section("general"):
                    volume_cf.set("volume", "broadcast_volume", "50")
                    project_cf.set("general", "init_player_state", "-1")
                    project_cf.set("general", "current_uri", "")
                else:
                    project_cf.add_section("general")
                    volume_cf.set("volume", "broadcast_volume", "50")
                    project_cf.set("general", "init_player_state", "-1")
                    project_cf.set("general", "current_uri", "")

                with open(PROJECT_CONFIG, "w") as f:
                    project_cf.write(f, space_around_delimiters=False)
                os.system("sync")

                self.player_current_volume = int(volume_cf.get("volume", "broadcast_volume"))
                self.init_player_state = int(project_cf.get("general", "init_player_state"))
                self.current_uri = project_cf.get("general", "current_uri")

        #设置mac
        self.mac = self._get_mac_address()

    """
        desc:
            获取设备mac地址
    """
    def _get_mac_address(self): 
        mac=uuid.UUID(int = uuid.getnode()).hex[-12:] 
        return ":".join([mac[e:e+2] for e in range(0,11,2)]).replace(":", "").lower()

    """
        desc:
            获取设置出局ip地址
    """
    def _get_host_ip(self):
        try:
            s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
            s.connect(('8.8.8.8',80))
            ip=s.getsockname()[0]
        finally:
            s.close()
        return ip
    
class MulticastConfig(object):
    def __init__(self):
        speaker_cf.read(SPEAKER_CONFIG_FILE, encoding='utf-8')
        volume_cf.read(VOLUME_CONFIG_FILE, encoding='utf-8')
        self.network_caching = int(speaker_cf.get("multicast_player", "network_caching"))
        self.address = []
        for i in range(1, ADDRESS_COUNT + 1):
            item = {}
            try:
                col = speaker_cf.get("multicast_player", "address"+str(i))
                gpio = speaker_cf.get("multicast_player", "gpio"+str(i))
                volume = int(volume_cf.get("volume", "multicast_"+str(i)+"_volume"))
            except:
                continue
            if col:
                item["id"] = i
                item["priority"] = i
                item["update_status"] = 0
                item["player_status"] = 0
                item["available_status"] = 0
                item["counter"] = 0
                item["url"] = col
                item["ip"] = col.split("@", 1)[1].lstrip().rstrip().split(":", 1)[0]
                item["port"] = int(col.split("@", 1)[1].lstrip().rstrip().split(":", 1)[1])
                item["gpio"] = gpio
                item["volume"] = volume
                self.address.append(item)