<?php
/*
* @date 31/01/2020
* Classe que consome a API do Trello
* Serve para quando usuário, que tem sua key e token configurados no Trello e 
* salvos na tabela sistema.usuarios_trello uma vez configurações ok, toda solicitação
* assumida por esse usuário irá criar um card no trello com o número da solicitação - título.
* Se na criação da tarefa houver arquivos anexo, esses arquivos tb irão ser enviados
* para o card do trello.
* Além da key, token e membersId do usuário, dois parâmetros são de suma importâcia para o  correto funcionamento
* dessa classe. São eles: boardId e listId que identificam em qual "Quadro" e "Lista" desse quadro o cad será criado.
*
* Documentação oficial da API do Trello: https://developers.trello.com/reference
* 
* Para recuperar informações do usuário faça uma chamada CURL da seguinte forma:
*   curl --request GET --url 'https://api.trello.com/1/members/<nome_de_usuario>?key=<chave>&token=<token>'
* retornará um json com diversas informações dentre elas o campo "0" contém o memberid, o idBoards vai listar os
* quadras que o usuário pertence. Essas duas infomações serão uteis para o correto funcionamento da API.
*
* @todo
* - Adicinar comentários de andamentos da solicitação (e anexos)
* - Mover card para as demais lista do quadro
* - Tratamento quando uma solicitação muda o usuário 
*/
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();

class Agro_Utils_Trello {

    private $url = 'https://api.trello.com/1/';
    private $config = null;
    private $db = null;
    private $error = array(
        'Objeto usuário não pode ser nulo'
    );
    private $infoTrello = null;
    private $User = null;
    private $boardId = '53c55104bfe4a84149423a4e'; // Quadro Agronet
    private $listId = '53c55104bfe4a84149423a4f'; // Lista Backlog no Quadro Agronet
    private $keepFromSource = 'all';
    private $cardName = null;
    private $cardDescription = null;
    private $response = null;
    private $jsonBody = null;
    private $cardId = null;
    
    public function __construct($user) {
        $this->User = $user;
        $this->config = new Zend_Config_Ini('../application/config/application.ini', getenv('APPLICATION_ENV'));
        $this->setDb();
        $this->setUserInfo();
    }

    /*
    * Retorna a mensagem de erro
    */
    private function getError($idx) {
        return $this->error[$idx];
    }

    private function setDb() {
        try {
            $Adapter = Zend_Db::factory('PDO_PGSQL', $this->config->resources->db->params);
            Zend_Db_Table_Abstract::setDefaultAdapter($Adapter);
            $this->db = Zend_Db_Table::getDefaultAdapter();
            return true;
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
    
    // seta as informações da tabela sistema.usuarios_trello na variavel infoTrello do usuário logado
    private function setUserInfo() {

        if (is_object($this->User)) {
            try {
                $this->setDb();
                $sql = $this->db->select()
                    ->from(array('ut' => 'sistema.usuarios_trello'), array('id', 'trello_key', 'trello_token', 'trello_memberid'))
                    ->where('ut.id_usuario = ?', $this->User->id);
                $this->infoTrello = $this->db->fetchRow($sql);

                return true;
            } catch (Exception $e) {
                return $e->getMessage();
            }
        } else {
            throw new Exception($this->getError(0));
        }

        return false;
    }

    // mostra as informações do usuário para conexao api trello
    public function getUserInfo() {
        return $this->infoTrello;
    }

    public function setCardName($name) {
        $this->cardName = $name;
    }

    public function getCardName() {
        return $this->cardName;
    }

    public function setCardDescription($description) {
        $this->cardDescription = $description;
    }

    public function getCardDescription() {
        return $this->cardDescription;
    }

    /*
    * Adiciona um card no board (idList)
    */
    public function newCard() {
        try {
            $url = $this->url . 'cards';
            $trello = new Zend_Http_Client($url, array('maxredirects' => 0, 'timeout' => 30));
            $trello->setParameterGet(array(
                'key' => $this->getUserInfo()['trello_key'],
                'token' => $this->getUserInfo()['trello_token'],
                'idMembers' => $this->getUserInfo()['trello_memberid'],
                'keepFromSource' => $this->keepFromSource,
                'idList' => $this->listId,
                'name' => $this->getCardName(),
                'desc' => $this->getCardDescription(),
                'pos' => 'bottom'
            ));
            $trello->setMethod(Zend_Http_Client::POST);
            $this->response = $trello->request();
            $this->setJsonBody();
            $this->setCardId();
            return true;            
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    private function setJsonBody() {
        if (!is_null($this->response)) {
            $this->jsonBody = json_decode($this->response->getBody());
        }
    }

    public function getJsonBody() {
        return $this->jsonBody;
    }

    private function setCardId() {
        if (!is_null($this->jsonBody)) {
            $this->cardId = $this->jsonBody->{'id'};
        }
    }

    public function getCardId() {
        return $this->cardId;
    }
    
    /*
    * Enviar arquivo $filename para um card ($id) específico
    */
    public function addAttachment($id, $filename, $filepath) {
        try {
            $url = $this->url . 'cards/'.$id.'/attachments';
            $trello = new Zend_Http_Client($url, array('maxredirects' => 0, 'timeout' => 30));
            $trello->setParameterGet(array(
                'key' => $this->getUserInfo()['trello_key'],
                'token' => $this->getUserInfo()['trello_token'],
            ));
            $trello->setFileUpload($filepath.$filename, 'file');
            $trello->setMethod('POST');
            return $trello->request();
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
}
