<?php

require_once 'lib/abstract_preloaded_regular_screen.php';

class I24hDeviceListScreen extends AbstractPreloadedRegularScreen
    implements UserInputHandler
{
    const ID = 'device_list';
    private $plugin;
    private $session;

    public static function get_media_url_str()
    {
        return MediaURL::encode(
            array('screen_id' => self::ID));
    }

    public static function get_item_media_url_str($device_id)
    {
        return MediaURL::encode(
            array(
                'screen_id' => self::ID,
                'device' => $device_id
            ));
    }

    public function get_handler_id()
    {
        return self::ID;
    }

    public function __construct(I24hPlugin $plugin, $session)
    {
        parent::__construct(self::ID, I24hConfig::GET_DEVICE_LIST_FOLDER_VIEWS());

        $this->plugin = $plugin;
        $this->session = $session;

        UserInputHandlerRegistry::get_instance()->register_handler($this);
    }

    public function handle_user_input(&$user_input, &$plugin_cookies)
    {
        if ($user_input->handler_id == 'device_list' && $user_input->control_id == 'handle_enter'){
            $m  = MediaURL::decode($user_input->selected_media_url);
            hd_print('Unregister devide_id='.$m->device);

            if (!$this->session->delete_device($m->device)){
                return ActionFactory::show_error(false,'Ошибка удаления устройства');
            }

        }
        $reg_dev = $this->session->register_device($plugin_cookies);
        if ($reg_dev){


            $media_url = MediaURL::encode(
                array(
                    'screen_id' => self::ID,
                    'device' => null
                ));

            $items = $this->get_all_folder_items(
                $media_url, $plugin_cookies);

//            hd_print("FOLDER ITEMS: ".print_r($items,true));

            return ActionFactory::update_regular_folder(
                HD::create_regular_folder_range($items), true);
        }

        return ActionFactory::open_folder(MediaURL::encode(array('screen_id'=>I24hTopScreen::ID)),'Устройства');
    }

    public function get_all_folder_items(MediaURL $media_url, &$plugin_cookies)
    {
        $items = array();
        $devices = $this->session->get_device_list();
        foreach ($devices as $dev){
            $device_name = '['.$dev->device_type.'] - '.ucwords($dev->vendor).' '.$dev->model;
            if (!empty($dev->login_at)){
                $device_name .= ' - '.date("H:i d.m.y",strtotime($dev->login_at));
            }
            $items[] = array
            (
                PluginRegularFolderItem::media_url =>
                    self::get_item_media_url_str($dev->id),
                PluginRegularFolderItem::caption => $device_name,
                PluginRegularFolderItem::view_item_params => array
                (
                    ViewItemParams::icon_path => 'gui_skin://large_icons/tv.aai',
                    ViewItemParams::icon_scale_factor => 0.35,
                    ViewItemParams::item_detailed_icon_path => 'gui_skin://large_icons/tv.aai',
                    ViewItemParams::item_detailed_info =>
                        (!empty($dev->model)?"Модель:||".$dev->model.'||':'').
                        (!empty($dev->device_type)?"Тип устройства: ".$dev->device_type."||":'').
                        (!empty($dev->vendor)?"Vendor: ".$dev->vendor."||":'').
                        (!empty($dev->created_at)?"Дата регистрации:||".date("H:i d.m.y",strtotime($dev->created_at))."||":'').
                        (!empty($dev->login_at)?"Дата последнего входа:||".date("H:i d.m.y",strtotime($dev->login_at))."||":'').
                        (!empty($dev->version)?"Version:||".$dev->version."||":'').
                        (!empty($dev->serial)?"Serial:||".$dev->serial:'')
                )
            );
        }
        return $items;
    }

    public function get_action_map(MediaURL $media_url, &$plugin_cookies)
    {
        return array
        (
            GUI_EVENT_KEY_ENTER =>
                UserInputHandlerRegistry::create_action(
                    $this, 'handle_enter'),
            GUI_EVENT_KEY_INFO =>
                UserInputHandlerRegistry::create_action(
                    $this, 'handle_info'),
        );
    }

}