<?php

class PluginTorrentdownload extends Plugin
{

    public $config   = null;
    public $data     = null;
    public $settings = null;

    public function __construct()
    {
        // setup database
        $db = Database::getDatabase();

        // get the plugin config
        include(DOC_ROOT . '/plugins/torrentdownload/_plugin_config.inc.php');

        // load config into the object
        $this->config = $pluginConfig;
        $this->data   = $db->getRow('SELECT * FROM plugin WHERE folder_name = ' . $db->quote($this->config['folder_name']) . ' LIMIT 1');
        if ($this->data)
        {
            $this->settings = json_decode($this->data['plugin_settings'], true);
        }
    }

    public function getPluginDetails()
    {
        return $this->config;
    }

    public function uninstall()
    {
        // setup database
        $db = Database::getDatabase();
        
        // remove plugin specific tables
        $sQL = 'DROP TABLE plugin_torrentdownload_torrent';
        $db->query($sQL);
        $sQL = 'DROP TABLE plugin_torrentdownload_torrent_file';
        $db->query($sQL);
        
        return parent::uninstall();
    }

    public function connectUTorrent()
    {
        // utorrent library
        require_once('includes/uTorrentRemote.class.php');

        // connect torrent
        $uTorrentHost = $this->settings['utorrent_host'] . (strlen($this->settings['utorrent_port']) ? (':' . $this->settings['utorrent_port']) : '');
        $uTorrent     = new uTorrentRemote($uTorrentHost, $this->settings['utorrent_username'], $this->settings['utorrent_password']);

        return $uTorrent;
    }

    public function addUpdateTorrent($torrentDetail, $userId)
    {
        // setup database
        $db = Database::getDatabase();

        // get torrent hash for lookups
        $torrentHash = strtoupper($torrentDetail[0]);

        // connect uTorrent
        $uTorrent = $this->connectUTorrent();

        // check for update or add
        $existingTorrent = $db->getRow('SELECT id FROM plugin_torrentdownload_torrent WHERE user_id = ' . (int) $userId . ' AND torrent_hash = ' . $db->quote($torrentHash) . ' AND save_status=\'downloading\' LIMIT 1');
        if ($existingTorrent)
        {
            // update torrent details
            $dbQuery                   = new DBObject("plugin_torrentdownload_torrent", array("status", "torrent_name", "torrent_size", "download_percent", "downloaded",
                "uploaded", "download_speed", "upload_speed", "time_remaining", "save_path", "peers_connected", "peers_in_swarm", "seeds_connected", "seeds_in_swarm"), 'id');
            $dbQuery->id               = $existingTorrent['id'];
            $dbQuery->status           = $torrentDetail[21];
            $dbQuery->torrent_name     = substr($torrentDetail[2], 0, 255);
            $dbQuery->torrent_size     = $torrentDetail[3];
            $dbQuery->download_percent = $torrentDetail[4];
            $dbQuery->downloaded       = $torrentDetail[5];
            $dbQuery->uploaded         = $torrentDetail[6];
            $dbQuery->download_speed   = $torrentDetail[8];
            $dbQuery->upload_speed     = $torrentDetail[9];
            $dbQuery->time_remaining   = $torrentDetail[10];
            $dbQuery->save_path        = $torrentDetail[26];
            $dbQuery->peers_connected  = $torrentDetail[12];
            $dbQuery->peers_in_swarm   = $torrentDetail[13];
            $dbQuery->seeds_connected  = $torrentDetail[14];
            $dbQuery->seeds_in_swarm   = $torrentDetail[15];

            $rs = $dbQuery->update() === false ? false : true;

            $torrentFiles = $this->getTorrentFileListing($torrentHash);
            if (COUNT($torrentFiles[1]))
            {
                // delete any existing
                $db->query('DELETE FROM plugin_torrentdownload_torrent_file WHERE torrent_id=' . (int) $existingTorrent['id']);

                // add new
                foreach ($torrentFiles[1] AS $torrentFile)
                {
                    // add torrent details into database
                    $dbQuery             = new DBObject("plugin_torrentdownload_torrent_file", array("torrent_id", "file_name", "filesize"));
                    $dbQuery->torrent_id = substr($existingTorrent['id'], 0, 255);
                    $dbQuery->file_name  = $torrentFile[0];
                    $dbQuery->filesize   = $torrentFile[1];
                    $dbQuery->insert();
                }
            }

            return $rs;
        }
        else
        {
            // add torrent details into database
            $dbQuery                   = new DBObject("plugin_torrentdownload_torrent", array("user_id", "torrent_hash", "date_added", "status", "torrent_name", "torrent_size", "download_percent", "downloaded",
                "uploaded", "download_speed", "upload_speed", "time_remaining", "save_path", "peers_connected", "peers_in_swarm", "seeds_connected", "seeds_in_swarm")
            );
            $dbQuery->user_id          = (int) $userId;
            $dbQuery->torrent_hash     = $torrentHash;
            $dbQuery->date_added       = date("Y-m-d H:i:s", time());
            $dbQuery->status           = $torrentDetail[21];
            $dbQuery->torrent_name     = substr($torrentDetail[2], 0, 255);
            $dbQuery->torrent_size     = $torrentDetail[3];
            $dbQuery->download_percent = $torrentDetail[4];
            $dbQuery->downloaded       = $torrentDetail[5];
            $dbQuery->uploaded         = $torrentDetail[6];
            $dbQuery->download_speed   = $torrentDetail[8];
            $dbQuery->upload_speed     = $torrentDetail[9];
            $dbQuery->time_remaining   = $torrentDetail[10];
            $dbQuery->save_path        = $torrentDetail[26];
            $dbQuery->peers_connected  = $torrentDetail[12];
            $dbQuery->peers_in_swarm   = $torrentDetail[13];
            $dbQuery->seeds_connected  = $torrentDetail[14];
            $dbQuery->seeds_in_swarm   = $torrentDetail[15];

            $rs = $dbQuery->insert();

            return $rs;
        }
    }

    public function getTorrentFileListing($torrentHash)
    {
        // connect
        $uTorrent = $this->connectUTorrent();

        // get files
        return $uTorrent->GrabListOfFiles($torrentHash);
    }

}