<?php

App::uses('AppHelper', 'View/Helper');
App::uses('Folder', 'Utility');
App::uses('File', 'Utility');

/**
 * Custom Helper
 *
 * For custom theme specific methods.
 *
 * If your theme requires custom methods,
 * copy this file to /app/views/themed/your_theme_alias/helpers/custom.php and modify.
 *
 * You can then use this helper from your theme's views using $custom variable.
 *
 * @category Helper
 * @package  Bemmelhor
 * @version  1.0
 * @author   Fabricio S Costa <fabriciojf@gmail.com>
 *
 * @link     http://www.bemmelhor.org
 */
class ApiHelper extends AppHelper {

    /**
     * Other helpers used by this helper
     *
     * @var array
     * @access public
     */
    public $helpers = array(
        'Session',
    );

    /**
     * Itens Plano
     */
    public $type_plano = array(
        1 => 'SMS',
        2 => 'CRM',
        3 => 'Portabilidade'
    );
    public $type_plano_colors = array(
        1 => 'panel-info',
        2 => 'panel-primary',
        3 => 'panel-warning'
    );

    /**
     * Itens StatusCredit
     */
    public $status_credit = array(
        0 => 'Pending',
        1 => 'Completed',
    );

    /**
     * Campaign
     */
    public $status_campaign = array(
        0 => 'Inativa',
        1 => 'Ativa',
        2 => 'Finalizada'
    );

    /**
     * Tipos de Mailing
     */
    public $mailing_types = array(
        1 => 'Nome ; DDD ; Phone',
        2 => 'Nome ; DDD+Phone',
        3 => 'Nome ; DDD ; Phone ; P1 ; P2 ; P3 ; P4 ; P5',
        4 => 'Nome ; DDD+Phone ; P1 ; P2 ; P3 ; P4 ; P5',
        5 => 'Nome ; DDD+Phone1 ; DDD+Phone2 ; DDD+Phone3 ; DDD+Phone4',
        6 => 'Nome ; DDD+Phone1 ; DDD+Phone2 ; DDD+Phone3 ; DDD+Phone4 ; P1 ; P2 ; P3 ; P4 ; P5'
    );

    /**
     * Converte um plano de integer para label
     * @param int $type
     */
    public function typeLabel($type) {
        return $this->type_plano[$type];
    }

    /**
     * Retorna uma cor para cada type, com o objetivo de trocar a cor do panel
     * @param int $type
     */
    public function typeColor($type) {
        return $this->type_plano_colors[$type];
    }

    /**
     * Retorna os status possiveis para creditos
     * @param int $status
     */
    public function statusCredit($status) {
        return $this->status_credit[$status];
    }

    /**
     * Retorna os status possiveis para Campanhas
     * @param int $status
     */
    public function statusCampaign($status) {
        return $this->status_campaign[$status];
    }

    /**
     * Retorna o tipo de mailing
     * @param int $type
     */
    public function mailingTypes($type) {
        return $this->mailing_types[$type];
    }

    /**
     * Retorna o tipo de mailing
     * @param int $type
     */
    public function isAdmin() {
        return ($this->Session->read('Auth.User.role_id') == '1');
    }

    /**
     * Limpa acentos da palavra passada
     * @param unknown_type $str
     */
    public function sanitizeString($str) {
        $str = preg_replace('/[áàãâä]/ui', 'a', $str);
        $str = preg_replace('/[éèêë]/ui', 'e', $str);
        $str = preg_replace('/[íìîï]/ui', 'i', $str);
        $str = preg_replace('/[óòõôö]/ui', 'o', $str);
        $str = preg_replace('/[úùûü]/ui', 'u', $str);
        $str = preg_replace('/[ç]/ui', 'c', $str);
        $str = preg_replace('/[^a-z0-9]/i', '-', $str);
        return $str;
    }

    /**
     * Capturando os icones para tela de gravacoes
     */
    public function iconCall($app) {
        switch ($app) {
            case 'Queue' :
                return 'fa-users bg-blue';
            case 'Dial' :
                return 'fa-phone bg-green';
            case 'Transferred Call' :
                return 'fa-mail-forward bg-yellow';
            case 'Hangup' :
                return 'fa-times-circle bg-red';
            case 'Playback' :
                return 'fa-music bg-purple';
            case 'Macro' :
                return 'fa-random bg-aqua';
            case 'Goto' :
                return 'fa-random bg-blue';
            case 'BackGround' :
                return 'fa-microphone bg-purple';
            case 'Set' :
                return 'fa-map-marker bg-aqua';
            default :
                return 'fa-dot-circle-o bg-blue';
        }
    }

    /**
     * Verifica se a ligacao foi gravada
     */
    public function getLinkAudioView($date, $uniqueid, $linkedid, $id) {
        $date = new DateTime($date);
        $folder = $date->format('Ym');

        $filenameWav = __('/var/spool/asterisk/monitor/final/%s/%s.wav', $folder, $uniqueid);

        $filenameMp3 = __('/var/spool/asterisk/monitor/final/%s/%s.mp3', $folder, $uniqueid);

        $filenameLinkedid = __('/var/spool/asterisk/monitor/final/%s/%s.mp3', $folder, $linkedid);

        $download = '';
        if ((file_exists($filenameWav)) || (file_exists($filenameMp3)) ||
                (file_exists($filenameLinkedid))) {
            $download = '<a class="btn btn-primary btn-xs" href="' . Router::url(array(
                        'plugin' => false,
                        'admin' => true,
                        'controller' => 'calls',
                        'action' => 'download', $id, true
                    )) . '"><span class="fa fa-cloud-download"></span>&nbsp;&nbsp;Baixar &Aacute;udio</a>&nbsp;&nbsp;' .
                    '<a class="btn btn-primary btn-xs" href="' . Router::url(array(
                        'plugin' => false,
                        'admin' => true,
                        'controller' => 'calls',
                        'action' => 'download', $id
                    )) . '"><span class="fa fa-play-circle"></span>&nbsp;&nbsp;Ouvir &Aacute;udio</a>';
        }
        return $download;
    }

    /**
     * Verifica se a ligacao foi gravada
     */
    public function getLinkAudio($date, $uniqueid, $linkedid, $id, $src, $dst) {
        $date = new DateTime($date);
        $folder = $date->format('Ym');

        if (Configure::read('Blacklist.ramais') != null) {
            if (in_array($src, Configure::read('Blacklist.ramais')) ||
                    in_array($dst, Configure::read('Blacklist.ramais'))) {
                return;
            }
        }

        $filenameWav = __('/var/spool/asterisk/monitor/final/%s/%s.wav', $folder, $uniqueid);

        $filenameMp3 = __('/var/spool/asterisk/monitor/final/%s/%s.mp3', $folder, $uniqueid);

        $filenameLinkedid = __('/var/spool/asterisk/monitor/final/%s/%s.mp3', $folder, $linkedid);

        $download = '';
        if ((file_exists($filenameWav)) || (file_exists($filenameMp3)) ||
                (file_exists($filenameLinkedid))) {
            $download = '&nbsp;&nbsp;<a href="' . Router::url(array(
                        'plugin' => false,
                        'admin' => true,
                        'controller' => 'calls',
                        'action' => 'download', $id, true
                    )) . '" class="font-icon-size"><span class="fa fa-cloud-download"></span></a>&nbsp;&nbsp;' .
                    '<a href="' . Router::url(array(
                        'plugin' => false,
                        'admin' => true,
                        'controller' => 'calls',
                        'action' => 'download', $id
                    )) . '" class="font-icon-size"><span class="fa fa-play-circle"></span></a>';
        }
        return $download;
    }

    /**
     * Verifica se a ligacao foi gravada
     */
    public function getLinkAudioByController($date, $uniqueid, $linkedid, $id, $src, $dst, $model = 'cdr_cleanables') {
        $date = new DateTime($date);
        $folder = $date->format('Ym');

        if (Configure::read('Blacklist.ramais') != null) {
            if (in_array($src, Configure::read('Blacklist.ramais')) ||
                    in_array($dst, Configure::read('Blacklist.ramais'))) {
                return;
            }
        }

        $filenameWav = __('/var/spool/asterisk/monitor/final/%s/%s.wav', $folder, $uniqueid);

        $filenameMp3 = __('/var/spool/asterisk/monitor/final/%s/%s.mp3', $folder, $uniqueid);

        $filenameLinkedid = __('/var/spool/asterisk/monitor/final/%s/%s.mp3', $folder, $linkedid);

        $download = '';
        if ((file_exists($filenameWav)) || (file_exists($filenameMp3)) ||
                (file_exists($filenameLinkedid))) {
            $download = '&nbsp;&nbsp;<a href="' . Router::url(array(
                        'plugin' => false,
                        'admin' => true,
                        'controller' => 'cdr_cleanables',
                        'action' => 'download', $id, true
                    )) . '" class="font-icon-size"><span class="fa fa-cloud-download"></span></a>&nbsp;&nbsp;' .
                    '<a href="' . Router::url(array(
                        'plugin' => false,
                        'admin' => true,
                        'controller' => 'cdr_cleanables',
                        'action' => 'download', $id
                    )) . '" class="font-icon-size"><span class="fa fa-play-circle"></span></a>';
        }
        return $download;
    }

    /**
     * Verifica se a ligacao foi gravada
     */
    public function getAllFilesByUniqueid($date, $uniqueid, $linkedid, $id, $src, $dst) {
        $date = new DateTime($date);
        $folder = $date->format('Ym');

        if (Configure::read('Blacklist.ramais') != null) {
            if (in_array($src, Configure::read('Blacklist.ramais')) ||
                    in_array($dst, Configure::read('Blacklist.ramais'))) {
                return;
            }
        }

        $baseid = explode(".", $uniqueid);
        $dir = new Folder('/var/spool/asterisk/monitor/final/'.$folder);
        $files = $dir->find($baseid[0].'.*');

        $download = '';
        foreach ($files as $currentFile) {
            $file = new File($dir->pwd() . DS . $currentFile);
            $fileinfo = $file->info();

            $downloadLink = '<a class="btn btn-primary btn-xs" href="' . Router::url(array(
                        'plugin' => false,
                        'admin' => true,
                        'controller' => 'calls',
                        'action' => 'admin_direct_download', $folder, $fileinfo['basename'], true
                    )) . '"><span class="fa fa-cloud-download"></span>&nbsp;&nbsp;Baixar</a>&nbsp;&nbsp;' .
                    '<a class="btn btn-primary btn-xs" href="' . Router::url(array(
                        'plugin' => false,
                        'admin' => true,
                        'controller' => 'calls',
                        'action' => 'admin_direct_download', $folder, $fileinfo['basename']
                    )) . '"><span class="fa fa-play-circle"></span>&nbsp;&nbsp;Ouvir</a>';

            $download .= sprintf('<tr><td>%s </td><td>%s </td><td>%s </td><td>%s </tr>',
                    $fileinfo['filename'],
                    $fileinfo['extension'],
                    $fileinfo['filesize'],
                    $downloadLink);

        }
        return $download;
    }


    /**
     * Capturando os icones para tela de gravacoes
     */
    public function translate($term) {
        switch ($term) {
            case 'Queue' :
                return 'Entrou na <b>Fila</b> e se conectou ao ramal ';
            case 'Dial' :
                return '<b>Discou</b> para ';
            case 'Transferred Call' :
                return 'Solicitou <b>Transfer&ecirc;ncia</b> : ';
            case 'Hangup' :
                return 'Desconectou ';
            case 'Playback' :
                return 'Ouviu um &aacute;udio ';
            case 'Macro' :
                return 'Entrou em uma rotina interna de valida&ccedil;&atilde;o ';
            case 'Goto' :
                return 'Entrou em uma rotina interna de valida&ccedil;&atilde;o ';
            case 'BackGround' :
                return 'Ouviu um &aacute;udio da <b>URA</b> ';
            case 'Set' :
                return 'Setou um valor interno ';
            case 'ANSWERED' :
                return '<span class="text-green">Atendido</span>';
            case 'NO ANSWER' :
                return '<span class="text-red">N&atilde;o Respondido</span>';
            case 'BUSY' :
                return '<span class="text-red">Ocupado</span>';
            case 'FAILED' :
                return '<span class="text-red">Falha ao Realizar Liga&ccedil;&atilde;o</span>';
            default :
                return '';
        }
    }

    /**
     * Configuracao para alocar Div Temporizado dentro da view
     * ex:
     * <?php echo $this->Api->refresh_div('monitor_telecom_wginuse', $this->Html->url(array(
     * 			         	'plugin' => false,
     * 			           	'admin' => true,
     * 			           	'controller' => 'monitor_telecom',
     * 			           	'action' => 'wginuse'
     * 			         )
     * 			   ),1000); ?>
     */
    public function refresh_div($div, $url, $time = 5000) {
        return "<script type=\"text/javascript\">
                        setTimeout(function(){
                                $.ajax({
                                        url: \"" . $url . "\",
                                        cache: false,
                                        success: function(data){
                                                $(\"#" . $div . "\").html(data);
                                        }
                                });
                        }, " . $time . ");
                </script>";
    }

    public function refresh_div_now($div, $url) {
        return "<script type=\"text/javascript\">
                        function refresh_now_" . $div . "(){
                                $.ajax({
                                        url: \"" . $url . "\",
                                        cache: false,
                                        success: function(data){
                                                $(\"#" . $div . "\").html(data);
                                        }
                                });
                        };
                </script>";
    }

    /**
     * Padrao de configuracao para SoapClient
     * Ver @MonitorTelecomController.php
     *
     * App::uses('ApiHelper', 'View/Helper');
     *
     * public function admin_index() {
     * 		$client = new SoapClient(null, ApiHelper::soapClientConf());
     * }
     */
    public static function soapClientConf() {
        return array(
            'location' => 'http://' . Configure::read('Telecom.host') . '/bmtelecomws/monitor.php',
            'uri' => 'http://' . Configure::read('Telecom.host') . '/bmtelecomws/',
            'trace' => 1);
    }

    /**
     * Conexao Asterisk Rest
     */
    public static function urlRestAsterisk($parameter = 'login') {

        $baseurl = 'http://' . Configure::read('Telecom.host') . ':8088/asterisk/mxml?';
        $params = array(
            'login' => $baseurl . 'action=Login&username=http&secret=cp65482jf',
            'core_channels' => $baseurl . 'action=CoreShowChannels',
            'queue_status' => $baseurl . 'action=QueueStatus',
            'commands' => $baseurl . 'action=ListCommands',
            'reload' => $baseurl . 'action=Reload',
        );
        if (isset($params[$parameter])) {
            return $params[$parameter];
        }
        return $baseurl . 'action=' . $parameter;
    }

    /**
     * Captura os dados do asterisk no padrao xml
     */
    public static function getRestAsterisk($action = 'core_channels') {

    	$data = '';

        $baseurl = 'http://' . Configure::read('Telecom.host') . ':8088/asterisk/mxml?';
        $matches = '';

        try {

	        //Request data via CURL
	        $curl = curl_init();
	        curl_setopt($curl, CURLOPT_URL, ApiHelper::urlRestAsterisk('login'));
	        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
	        curl_setopt($curl, CURLOPT_HEADER, true);
	        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	        curl_setopt($curl, CURLOPT_TIMEOUT, 5000);
	        curl_setopt($curl, CURLOPT_TIMEOUT_MS, 5000);
	        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3000);
	        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, 3000);
	        curl_setopt($curl, CURLOPT_NOSIGNAL, 1);
	        $data_login = curl_exec($curl);
	        curl_close($curl);

	        preg_match_all('|Set-Cookie: (.*);|U', $data_login, $matches);
	        $cookies = implode(';', $matches[1]);

	        $curl2 = curl_init();
	        curl_setopt($curl2, CURLOPT_URL, ApiHelper::urlRestAsterisk($action));
	        curl_setopt($curl2, CURLOPT_FOLLOWLOCATION, false);
	        curl_setopt($curl2, CURLOPT_HEADER, false);
	        curl_setopt($curl2, CURLOPT_RETURNTRANSFER, true);
	        curl_setopt($curl2, CURLOPT_COOKIE, $cookies);
	        curl_setopt($curl2, CURLOPT_TIMEOUT, 5000);
	        curl_setopt($curl2, CURLOPT_TIMEOUT_MS, 5000);
	        curl_setopt($curl2, CURLOPT_CONNECTTIMEOUT, 3000);
	        curl_setopt($curl2, CURLOPT_CONNECTTIMEOUT_MS, 3000);
	        curl_setopt($curl2, CURLOPT_NOSIGNAL, 1);
	        $data = curl_exec($curl2);

        } finally {

	        curl_setopt($curl2, CURLOPT_URL, ApiHelper::urlRestAsterisk('logoff'));
	        curl_setopt($curl2, CURLOPT_FOLLOWLOCATION, false);
	        curl_setopt($curl2, CURLOPT_HEADER, true);
	        curl_setopt($curl2, CURLOPT_RETURNTRANSFER, true);
	        curl_exec($curl2);
	        curl_close($curl2);

        }

        return $data;
    }

    /**
     * Retorna um parametro do seettings, caso ele não exista retorna o falor
     * passado em $default
     * @param unknown $default
     */
    public static function getSetting($param, $default) {
        if (Configure::read($param) != '') {
            return Configure::read($param);
        }
        return $default;
    }

    /**
     * Retorna a saida da execucao do Curl
     */
    public static function getCurl($url, $typeRequest) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $typeRequest);
        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }

    public static function hostIsUp($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

        curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($curl2);

        return $info['http_code'] === 200;
    }

    /**
     * Mostra o sql da consulta realizada
     */
    public function showsql($object) {
        $log = $object->getDataSource()->getLog(false, false);
        debug($log);
    }

    /**
     * Formata horas acima de 24
     */
    function formatHour($sec) {
        $t = new DateTime("@" . $sec);
        $r = new DateTime("@0");
        $i = $t->diff($r);
        $h = intval($i->format("%a")) * 24 + intval($i->format("%H"));
        return $h . ":" . $i->format("%I:%S");
    }

}
