<?php
namespace Teknisa\Libs\Service;

use Teknisa\Libs\Util\SMTP;
use Teknisa\Libs\Util\Environment;

class ReportBug {

    const SUBJECT = 'Novo Bug Reportado';
    const MAIL_TEMPLATE =  __DIR__.'/../Util/EmailTemplates/report_bug.html';
    const DEFAULT_TYPE = 'B';
    const TYPE_NAME = array(
        'B' => 'Bug',
        'I' => 'Melhoria'
    );

    private $environment;
    private $smtp;

    public function __construct(Environment $environment, SMTP $smtp){
        $this->environment = $environment;
        $this->smtp = $smtp;
    }

    private function buildTable($data, $columns){
        $table = '<table style="font-family: \'Open Sans\', arial !important;font-size: 14px;color:#333333;margin-left:15px;">';
        $firstColumn = array_shift($columns);
        foreach($data as $item){
            $table .= '<tr>';
            $table .= '<td><li>'.$item[$firstColumn].'</li></td>';
            foreach($columns as $column){
                $table .= '<td>'.$item[$column].'</td>';
            }
            $table .= '</tr>';
        }
        $table .= '</table>';
        return $table;
    }

    private function buildLiItems($data, $liStyle='margin-left:30px;'){
        $li = '';
        foreach($data as $item){
            $li .= '<li style="'.$liStyle.'">'.$item['name'].': '.$item['version'].'</li>';
        }
        return $li;
    }

    private function getTypeName($type){
        $type = \Zeedhi\Framework\Util\Functions::arrayKeyExists($type, self::TYPE_NAME) ? $type : self::DEFAULT_TYPE;
        return self::TYPE_NAME[$type];
    }

    private function buildHeader($replacedContents, $row){
        $replacedContents = str_replace('%user%', $this->environment->getCurrentUserName(), $replacedContents);
        $replacedContents = str_replace('%organization%', $this->environment->getCurrentOrganizationId(), $replacedContents);
        $replacedContents = str_replace('%type%', $this->getTypeName($row['TYPE']), $replacedContents);
        $replacedContents = str_replace('%projectName%', $row['versionData']['name'], $replacedContents);
        $replacedContents = str_replace('%description%', nl2br($row['DESCRIPTION']), $replacedContents);
        return $replacedContents;
    }

    private function buildVersionData($replacedContents, $row){
        $versionData = $row['versionData'];
        $replacedContents = str_replace('%projectVersion%', $versionData['version'], $replacedContents);
        $dependencies = '';
        foreach($versionData['dependencies'] as $key=>$value){
            if(count($value) > 0){
                $dependencies .= '<p style="margin-left:30px;margin-top:0px"><b>'.$key.'</b>';
                $dependencies .= $this->buildTable($value, array('name', 'version'));
                $dependencies .= '</p>';
            }
        }
        $replacedContents = str_replace('%dependencies%', $dependencies, $replacedContents);
        return $replacedContents;
    }

    private function buildServerData($replacedContents){
        $serverData = array(
            array('name' => 'Apache', 'version' => apache_get_version()),
            array('name' => 'PHP', 'version' => phpversion()),
            array('name' => 'SO', 'version' => php_uname())
        );
        $replacedContents = str_replace('%serverData%', $this->buildLiItems($serverData), $replacedContents);
        return $replacedContents;
    }

    private function buildDBData($replacedContents){
        $serverData = array(
            array('name' => 'Oracle', 'version' => oci_client_version())
        );
        $replacedContents = str_replace('%dbData%', $this->buildLiItems($serverData), $replacedContents);
        return $replacedContents;
    }

    private function buildExtraData($replacedContents, $row){
        $replacedContents = str_replace('%reportedWidget%', $row['widgetName'], $replacedContents);
        $replacedContents = str_replace('%reportedContainer%', $row['containerName'], $replacedContents);
        $replacedContents = str_replace('%reportedUrl%', $row['url'], $replacedContents);

        $navigator = $row['navigator'];
        $browserData = array(
            array('name' => 'Nome', 'version' => $navigator['name']),
            array('name' => 'Fornecedor', 'version' => $navigator['vendor']),
            array('name' => 'Versão', 'version' => $navigator['version'])
        );
        $replacedContents = str_replace('%browserData%', $this->buildLiItems($browserData, 'margin-left:45px;'), $replacedContents);
        return $replacedContents;
    }

    private function getMailMessage($row) {
        $replacedContents = file_get_contents(self::MAIL_TEMPLATE);
        $replacedContents = $this->buildHeader($replacedContents, $row);
        $replacedContents = $this->buildVersionData($replacedContents, $row);
        $replacedContents = $this->buildServerData($replacedContents);
        $replacedContents = $this->buildDBData($replacedContents);
        $replacedContents = $this->buildExtraData($replacedContents, $row);
        return $replacedContents;
    }

    public function sendEmail($row){
        $address = $row['EMAIL'];
        $addressCC = explode(';', $row['CC']);
        $message = $this->getMailMessage($row);
        $this->smtp->setSubject(self::SUBJECT);
        $this->smtp->setFrom($this->environment->getCurrentEmail());
        $this->smtp->setFromName($this->environment->getCurrentUserName());
        $this->smtp->sendMail($message, $address, $addressCC);
    }
}