<?php

/**
 *
 * @package    symfony
 * @subpackage plugin
 * @author     davert <davert@ukr.net>
 */
class bugTrackerActions extends sfActions
{
    public function executeProxy(sfWebRequest $request)
    {
        $proxy = new sfBugTrackerProxy;
        $proxy->parse($request->getGetParameters());
        return sfView::NONE;
    }

    public function executeBugReport(sfWebRequest $request)
    {
        // $param = $request->getParameterHolder()->getAll();
        $attach = $request->getFiles();
        $param = $request->getParameter('bug_report');
        $user = $this->getUser();
        $param['username'] = '';
        if($user->isAuthenticated()){
            $param['username'] = $user->getUsername();
        }
        $this->writeToLog($param);
        // echo var_export($param, true)."\n".var_export($files, true);
        if (isset($param['screenshot']) && trim($param['screenshot']) != '') {
            if (stripos($param['screenshot'], 'data:') == 0) {
                // split the string on commas
                // $data[ 0 ] == "data:image/png;base64"
                // $data[ 1 ] == <actual base64 string>
                $data = explode(',', $param['screenshot']);
                $tmpfname = tempnam(sfConfig::get('sf_cache_dir'), "screen_");
                // open the output file for writing
                $ifp = fopen($tmpfname, 'wb');
                // we could add validation here with ensuring count( $data ) > 1
                fwrite($ifp, base64_decode($data[1]));
                // clean up the file resource
                fclose($ifp);
                $info = getimagesize($tmpfname);
                $ntmpfname = $tmpfname . image_type_to_extension($info[2]);
                rename($tmpfname, $ntmpfname);
                $attach[] = $ntmpfname;
            }
        }

        sfContext::getInstance()->getConfiguration()->loadHelpers('Partial');

        $issue_data = array('description' => get_partial('bugTracker/bug_report', $param));
        if(isset($param['msg']) && $param['msg'] != ''){
            $issue_data['subject'] = $param['msg'];
        }
        $this->redmineIssue($issue_data);

        $message = Swift_Message::newInstance();
        $setFrom = sfConfig::get('app_email_sender', 'noreply@' . $request->getHost());
        $emailTo = sfConfig::get('app_bug_tracker_email');
        $message->setFrom($setFrom)->setContentType('text/html; charset=utf-8');
        if($emailTo){
            $emailTo = explode(',', $emailTo);
        }
        $message->setSubject('Новое сообщение об ошибке в проекте «' . sfConfig::get('app_bug_tracker_project') . '»');
        try {
            $message->setBody(nl2br(get_partial('bugTracker/bug_report', $param)));
        } catch (Exception $e) {
            echo json_encode(array('status' => 'error', 'msg' => $e));
            return sfView::NONE;
        }

        if (!empty($attach)) {
            foreach ((array)$attach as $file) {
                $message->attach(Swift_Attachment::fromPath($file));
            }
        }
        if (count($emailTo) > 0) {
            $message->setTo($emailTo);
            try {
                $this->getMailer()->send($message);
            } catch (Exception $e) {
                echo json_encode(array('status' => 'error', 'msg' => $e->__toString()));
                return sfView::NONE;
            }
            echo json_encode(array('status' => 'ok'));
        } else {
            echo json_encode(array('status' => 'error', 'msg' => 'Empty emailTo'));
        }
        return sfView::NONE;
    }

    public function writeToLog($data)
    {
        $logger = new SplFileObject(sfConfig::get('sf_log_dir') . DIRECTORY_SEPARATOR . 'bug_tracker.log', 'a');
        $logger->fwrite(date('Y-m-d H:i:s') . "\n\n");
        $keys = array_keys($data);
        array_walk($keys, function (&$item) {
            $item = strlen($item);
        });
        rsort($keys, SORT_NUMERIC);
        $format = sprintf("%%-%ss: %%s\n", reset($keys));
        foreach ($data as $key => $value) {
            if ($value && is_array($value)) {
                $string = sprintf($format, $key, '');
                $logger->fwrite($string);
                $vformat = sprintf("   %%-%ss: %%s\n", reset($keys) - 3);
                foreach ($value as $vkey => $vvalue) {
                    $string = sprintf($vformat, $vkey, $vvalue);
                    $logger->fwrite($string);
                }
            } else {
                $string = sprintf($format, $key, $value);
                $logger->fwrite($string);
            }
        }
        $logger->fwrite("\n\n\n");
        unset($logger);
    }

    private function redmineIssue($data = array())
    {
        $redmine = sfConfig::get('app_bug_tracker_redmine');
        if(isset($redmine['key']) && $redmine['key'] && isset($redmine['project_id']) && $redmine['project_id'] && isset($redmine['url']) && $redmine['url']){
            $data['project_id'] = $redmine['project_id'];
            $data['tracker_id'] = '1';
            $data['status_id'] = '1';
            $data['priority_id'] = '4';
            if(!isset($data['subject'])){
                $data['subject'] = 'Новое сообщение об ошибке';
            }
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
            curl_setopt($ch, CURLOPT_URL, $redmine['url'] . '/issues.json');
            curl_setopt($ch, CURLOPT_HEADER, true);
            curl_setopt($ch, CURLOPT_USERPWD, $redmine['key'] . ':123');
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('issue' => $data)));
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_exec($ch);
            curl_close($ch);
        }
    }
}
