from fw import log
from fw import core
from app.model.channel import Channel,Channels

async def on_event():
    log.d('start')
    try:
        #サーバー情報を取得する
        guild=core.get_guild()
        if guild == None:
            log.d("end no guild")
            return
        
        #Discord上のチャンネルを取得する
        d_channels=guild.channels
        if d_channels is None:
            d_channels = []

        for d_channel in d_channels:
            c_id=d_channel.id
            c_name=d_channel.name
            c_category=d_channel.category
            c_type=d_channel.type
        
            #DB上のカテゴリIDを取得する
            c_category_id=0
            if c_category!=None:
                c_category_id=c_category.id

            #DB上
            channel=Channels().first(c_id)
            if channel==None:
                log.i("new:"+str(c_name))
                Channels().new(c_id,c_category_id,c_name,c_type)
                continue
        
            channel_id=channel.id
            if str(channel.c_category_id) !=str(c_category_id) or str(channel.c_name)!=str(c_name):
                log.i("set:"+str(c_name))
                Channels().set(channel_id,c_category_id,c_name)
                continue

    except Exception as e:
        print(e)
        log.e(str(e))

    log.d('end')
    return
