import codecs
import json
import urllib.request
from constants import constants, command_name_list
from telepot.namedtuple import KeyboardButton, ReplyKeyboardMarkup
from model.repositories import channel_repository
from bot import bot
from decorators.command import command

@command(command_name_list["listacanali"])
def get_all_channels(chat_id, message, **kwargs):
    bot.sendChatAction(chat_id, "typing")
    result = []
    for channel in channel_repository.find_all_channels():
        result.append([KeyboardButton(text = channel.name)])
    keyboard = ReplyKeyboardMarkup(keyboard=result, one_time_keyboard=True, selective=True)
    bot.sendMessage(chat_id, constants["selectChannel"], reply_markup=keyboard)
    return "/listaprogrammi"

def find_channel(name):
    url = constants["linkSky"] + "/" + constants["linkChannelList"]
    httpResult = urllib.request.urlopen(url)
    httpResult = codecs.getreader("UTF-8")(httpResult)
    channels = json.load(httpResult)
    for channel in channels:
        if name == channel["name"]:
            return channel["id"]