<?php
///////////////////////////////////////////////////////////////////////////

require_once 'lib/abstract_controls_screen.php';
require_once 'lib/control_factory.php';
require_once 'lib/sticker.php';

class SetupScreen extends AbstractControlsScreen
{
    const ID = 'setup';

    private static function get_default_mount_point()
    {
        $builtin_name = MainHelper::builtin_memory_folder_name();
        return "/mnt/runtime/default/emulated/0/$builtin_name/CloudDrive";
    }

    /////////////////////////////////////////////////////////////////////// 

    public function __construct()
    {
        parent::__construct(self::ID);
    }
    
    private function get_local_http_url()
    {
        $ip = HD::get_ip_addr();
        return $ip ? "http://$ip:19798" : "";
    }

    private function do_get_control_defs(&$plugin_cookies)
    {
        $defs = array();

        $status = HD::get($plugin_cookies, 'status', 0);
        $btn = "";
        if ($status == 1)
            $btn = 'button_disable';
        else
            $btn = 'button_enable';

        ControlFactory::add_button($defs, $this, null,
            $btn, '', T::t($btn), 600,
            array('button_caption_centered' => 1));

        if ($status == 0)
            return $defs;

        ControlFactory::add_vgap($defs, 30);

        $url = $this->get_local_http_url();
        if (!$url)
        {
            ControlFactory::add_label($defs,
                null, T::t('label_no_internet'),
                array('force_no_title' => 1));

            return $defs;
        }

        ControlFactory::add_label($defs,
            null, T::t1('label_open_url__1', $url),
            array('force_no_title' => 1));

        ControlFactory::add_button($defs, $this, null,
            'qr_code', '', T::t('button_show_qr_code'), 0,
            array('button_caption_centered' => 1));

        ControlFactory::add_vgap($defs, 30);

        ControlFactory::add_label($defs,
            null, T::t1('label_use_mount__1', self::get_default_mount_point()),
            array('force_no_title' => 1));

        ControlFactory::add_vgap($defs, 20);

        ControlFactory::add_label($defs,
            null, T::t('label_access'),
            array('force_no_title' => 1));

        ControlFactory::add_button($defs, $this, null,
            'show_builtin_memory', '',
            T::g('storage_detected_button_open_in_file_browser'), 0,
            array('button_caption_centered' => 1));

        return $defs;
    }

    public function get_control_defs(MediaURL $media_url, &$plugin_cookies)
    {
        return $this->do_get_control_defs($plugin_cookies);
    }

    public function download_qr($size = 500)
    {
        $qr_url = $this->get_local_http_url();
        $param = urlencode($qr_url);

        $path = DuneSystem::$properties['tmp_dir_path'] . "/qr.jpg";
        $fp = fopen($path, "w");
        if (!$fp)
            return null;

        $url = "https://api.qrserver.com/v1/create-qr-code/?size=${size}x${size}&format=jpeg&data=$param&qzone=4";

        $opts = array(
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => 0,
            CURLOPT_FILE => $fp);

        try {
            $res = HD::http_get_document($url, $opts);
        } catch (Exception $ex) {
            $res = false;
        }

        fclose($fp);

        if ($res === false) {
            hd_print("Failed to create QR-code");
            return ActionFactory::show_error(
                false, T::g('error_dialog_title'));
        }

        return $path;
    }

    public function show_qr(&$plugin_cookies)
    {
        $path = $this->download_qr(500);
        $icon_url = "file://$path";

        $smart = array(
            'items' => array(
                Sticker::gap_arr(50),
                Sticker::icon_arr($icon_url, 500, 500)));
        $text = json_encode($smart);

        $defs = array();
        ControlFactory::add_smart_label($defs, null, $text);
        ControlFactory::add_vgap($defs, 480);
        ControlFactory::add_close_dialog_button($defs,
            T::g('button_close'), 300);
        return ActionFactory::show_dialog(
            T::t('title_qr_code'), $defs, true, 600);
    }

    private function show_builtin_memory(&$plugin_cookies)
    {
        $builtin_name = MainHelper::builtin_memory_folder_name();

        $ffset = ConfigUtils::load_firmware_features();
        $url = isset($ffset['url_sdcard']) ?
            "sdcard://$builtin_name" : 'internal_memory://';

        return ActionFactory::launch_media_url_ext(
            "embedded_app://{name=file_browser}{url=$url}",
            T::g('built_in_memory_title'));
    }

    public function handle_user_input(&$user_input, &$plugin_cookies)
    {
        hd_print('Setup screen: handle_user_input:');
        foreach ($user_input as $key => $value)
            hd_print("  $key => $value");

        $control_id = HD::get($user_input, 'control_id', 'none');
        $ipath = DuneSystem::$properties['install_dir_path'];

        if ($control_id == 'button_disable' || $control_id == 'button_enable')
        {
            $old_status = HD::get($plugin_cookies, 'status', 0);

            $new_status = 0;
            if ($control_id == 'button_enable')
                $new_status = 1;

            if ($new_status == $old_status)
                return null;

            $plugin_cookies->status = $new_status;
            $plugin_cookies->sources_shown =
                $new_status ? "yes" : "no";

            $a = $this->custom_action(
                $new_status ? 'enable_cd2' : 'disable_cd2');

            return ActionFactory::reset_controls(
                $this->do_get_control_defs($plugin_cookies), $a, -1);
        }

        if ($control_id == 'enable_cd2')
        {
            $cmd = "$ipath/bin/launch.sh enable";
            system($cmd);

            return null;
        }
        
        if ($control_id == 'disable_cd2')
        {
            system('sync');

            $cmd = "$ipath/bin/stop.sh";
            system($cmd, $ret);

            // TODO: revise
/*
            // Actual reboot action
            $a = ActionFactory::change_settings(null, true, false);

            $defs = array();
            ControlFactory::add_label($defs, null,
                T::g('setup_setting_updated_reboot_needed'));
            ControlFactory::add_vgap($defs, 20);
            ControlFactory::add_custom_close_dialog_and_apply_button($defs,
                'reboot_now', T::g('setup_setting_updated_reboot_now'), 600, $a,
                array('button_caption_centered' => 1));
            ControlFactory::add_vgap($defs, 10);
            
            return ActionFactory::show_dialog(
                T::g('setup_setting_updated_title'), $defs, false);
*/

            $defs = array();
            ControlFactory::add_vgap($defs, -22);
            $actions = array(GUI_EVENT_TIMER =>
                $this->custom_action(
                    'sleep_in_dialog', null, 10000, 10000));
            $timer = ActionFactory::timer(0);
            return ActionFactory::show_dialog(
                T::g('please_wait'), $defs, false, 500,
                array('actions' => $actions, 'timer' => $timer));
        }

        if ($control_id == 'sleep_in_dialog')
        {
            hd_print("Sleep: start");
            sleep(2);
            hd_print("Sleep: end");
            return ActionFactory::close_dialog();
        }

        if ($control_id == 'qr_code')
            return $this->show_qr($plugin_cookies);

        if ($control_id == 'show_builtin_memory')
            return $this->show_builtin_memory($plugin_cookies);

        return null;
    }
}
