<?php
include_once('c_mo_db.php') ;

// сделать нормальные именования массивов/переменных/функций

class c_page_cab_mo_db_term extends c_page_cab_mo_db
{
    public $h1='Лог терминала' ;
    public $use_fusioncharts=1;

    function get_cur_page_meta_tags() {
        if ($this->rec_personal['pkey']) $this->h1='Лог работы терминала при проверке сотрудника '.$this->rec_personal['obj_name'] ;
    }

    function set_head_tags() {
        parent::set_head_tags() ;
        $this->HEAD['css'][]=_PATH_TO_EXT.'/log/term_log.css' ;
        $this->HEAD['js'][]=_PATH_TO_EXT.'/log/term_log.js' ;
    }

    function block_main()
    { $this->page_title() ;
        include_once(_DIR_EXT.'/log/i_term_log.php') ;

//        $rec_terminal=ESMO()->get_terminal_by_id($this->rec_mo['terminal_id']) ;

        ?>
        <div class=" sky-form no_box_shadow view-log_btn-panel">
            <button class="button v2 view-log_btn" cmd="log/get_term_log" term_id="<?echo $this->rec_mo['terminal_pkey']?>" filename="terminal" cur_mo="<?echo _CUR_ID?>" onclick="$j('#load_gif').removeAttr('hidden')">Открыть terminal.log</button>
            <button class="button v2 view-log_btn" cmd="log/get_term_log" term_id="<?echo $this->rec_mo['terminal_pkey']?>" filename="terminald" cur_mo_start="<?echo $this->rec_mo['c_data']?>" cur_mo_end="<?echo $this->rec_mo['e_data']?>" onclick="$j('#load_gif').removeAttr('hidden')">Открыть terminald.log</button>
        </div>
        <div id="header"></div>
        <div id="show_log">
        </div>
        <div class="log-loading" id="loading_layer">
            <img id="load_gif" src="/images/loading15.gif" hidden>
        </div>
        <?

//        $log_fname = TERM_LOG()->get_term_log_from_url('https://'.$rec_terminal['ip'].'/log/terminal.log'); //TODO: поменять https на _MAIN_PROTOCOL



//        if ($log_fname) {
//            TERM_LOG()->term_log_prettify($log_fname);
//            TERM_LOG()->print_log(['cur_mo'=>_CUR_ID]);
//        } else {
//            echo 'Не удалось загрузить лог с терминала.';
//        }
    }

    function view_log($log_fname)
    {
        $error_array=[];
        $first_time = null; $last_time = null;
        $ts1=fixed_time() ;
        echo 'Используем лог '.hide_server_dir($log_fname).'<br>' ;
        $text=file_get_contents($log_fname) ;

        $arr=explode("\n",$text) ;

//        damp_array($arr);
        if (!$arr[_sizeof($arr)-1]) unset($arr[_sizeof($arr)-1]); //убираем последний элемент т.к. файл заканчивается \n и последний пустой
        echo 'Прочитано '._sizeof($arr).' строк <br>' ;
        // первый проход - разбиваем на сеансы МО
        $t_last=0 ; $seans_start=0 ; $arr33=array() ; $seans_indx=0 ; $arr_mo_id_by_seans_indx=array() ;

        foreach($arr as $line=>$value)
        {
            $line_status='';
            $comment='';
            $line_array=explode(' - ',$value) ;

            if (_sizeof($line_array)>1) {
                $time = date_create($line_array[0]) ;
                if (!$first_time) $first_time=$time;
                else $last_time=$time;
                if (is_object($time)) {
                    $h=date_format($time,'H')*60*60*1000000 ;
                    $i=date_format($time,'i')*60*1000000 ;
                    $s=date_format($time,'s')*1000000 ;
                    $u=date_format($time,'u') ;
                    $t_now=$h+$i+$s+$u ;
                    // $dt - интервал времени в микросекундах
                    $dt=($t_last)? $t_now-$t_last:'';

                    $dt=$dt/1000 ;
                }
                $comment=trim($line_array[1]) ;
//                $comment=trim(str_replace(array('info:','error:'),'',$comment)) ;
                if (mb_strpos($comment,'error:')!==false) {
                    $line_status='commentError';
                    $error_array[$comment]['cnt']++;
                }
                $dt_seans=($seans_start)? $t_now-$seans_start:'' ;
                $dt_seans=$dt_seans/1000 ;

                $t_last=$t_now ;
//                if ($comment=='Got hid auth') $seans_indx++ ;
                if ($comment=='info: Got hid auth' or (stripos($comment,'info: Got number')!==false)) $seans_indx++ ;
//                if ($comment=='Got hid auth') $seans_start=$t_now ;
                if ($comment=='info: Got hid auth' or (stripos($comment,'info: Got number')!==false)) $seans_start=$t_now ;
                $mo_id=0 ;
                if (stripos($comment,'medexam')!==false) {
                    if (preg_match_all('/\"medexam\"\:\"(.+?)\"/is',$comment,$matches,PREG_SET_ORDER)) { $mo_id=$matches[0][1] ;
                        $arr_mo_id_by_seans_indx[$seans_indx]=$mo_id ;
                    }
                }
            } else {
                // строка не разбивается по стандартному шаблону 2019-04-24T04:55:21.660Z - info: readCard: webcam failed. (" - ")
                $error_array[$value]['cnt']++;
//                $error_array[$comment]['line'][]=$line;
                $time=null;
                $seans_indx=null;
                $mo_id=null;
                $dt=null;
                $dt_seans=null;
                $comment = $value;
                $line_status='errorJS';
            }

            $data=array('time_log'=>$time,
                'dt'=>$dt,
                'dt_seans'=>$dt_seans,
                'seans_indx'=>$seans_indx,
                'mo_id'=>$mo_id,
                'comment'=>$comment,
                'line_status'=>$line_status,
            ) ;
            $arr33[$line]=$data ;

            //if ($line>100) break ;

        }
        echo 'Найдено '._sizeof($arr_mo_id_by_seans_indx).' сеанса МО<br>' ;
        //damp_array($arr_mo_id_by_seans_indx) ;

        $recs=array() ;
        foreach($arr33 as $rec) if ($arr_mo_id_by_seans_indx[$rec['seans_indx']]==$this->rec_mo['pkey']) $recs[]=$rec  ;

        $ts2=fixed_time() ;
        $dt=$ts2-$ts1 ;
        echo 'Время обработки лога - '.round($dt,3).' сек<br>' ;
        //echo '_sizeof='._sizeof($recs).'<br>' ;

        // второй проход - выводим таблицу
        if (_sizeof($recs)) {
            ?>
            <h1>Таблица логов</h1>
            <table id="terminal_log" class="basic fz_small left full auto">
                <tr>
                    <th>№</th>
                    <th>Время</th>
                    <th>Время по сеансу</th>
                    <th class="left">Длительность операции</th>
                    <th>Описание</th>
                    <th>data</th>
                </tr>
                <?
                foreach($recs as $i=>$rec) {
                    $comment_array=[];
                    $json_text='';
                    $json_start=mb_stripos($rec['comment'],'{');
                    if ($json_start!==false) {
                        $json_text=mb_stristr($rec['comment'],'{');
                        $comment_array=json_decode($json_text,true);
                    }
                    ?>
                    <tr>
                        <td><? echo $i+1?></td>
                        <td><?if (is_object($rec['time_log'])) echo date_format($rec['time_log'],'d.m.Y H:i:s.u')?></td>
                        <td class="nowrap"><? echo ($i)? '+ '.number_format($rec['dt_seans'],0,'.',' ').' мс':'-'?></td>
                        <td class="nowrap"><? echo ($i)? number_format($rec['dt'],0,'.',' ').' мс':'-'?></td>
                        <td class="<?if ($rec['line_status']) echo ' '.$rec['line_status']?>"><?echo $rec['comment']?></td>
                        <td><?if ($comment_array) damp_array($comment_array,1,-1)?></td>
                    </tr>
                    <?
                    if ($rec['comment']=='Destroying progress message controller scope') break ;
                }

                ?>
            </table>
            <style type="text/css">
                #terminal_log td.errorJS {background-color: #ffd7d7}
                #terminal_log td.commentError {background-color: #ffbec4}
            </style>
            <?
        } ;
    }




}

?>
