<?
include_once(_DIR_EXT.'/HTML/c_page_XML_AJAX.php');;
class c_page_ajax extends c_page_XML_AJAX
{

    function get_disk_info()
    {   $to_data=strip_tags($_POST['data']) ;
        $to_time=strtotime($to_data) ;
        include_once(_DIR_TO_MODULES.'/engine/i_disk.php') ;
        ob_start() ;
        echo '<strong>Данные на дату: '.date('d.m.Y',$to_time).'</strong><br>' ;
         $recs=execSQL('select * from obj_site_disk where c_data='.$to_time.' order by obj_name') ;

         // выводим полученыый массив в три колонки по типу директорий
         ?><table id="dir_info"><tr><?
         ?><td><? $this->show_dir_info('Пользователькие данные',$recs,USER_DATA) ;?></td><?
         ?><td><? $this->show_dir_info('Временные файлы',$recs,TEMP_FILE) ; ?></td><?
         ?><td><? $this->show_dir_info('Исходный код ЭСМО',$recs,SOURCE_CODE) ; ?></td><?
         ?></tr></table>
          <style type="text/css">
              table#dir_info{width:100%;table-layout:fixed;}
              table#dir_info td{width:auto;vertical-align: top;}
          </style>
          <?
        $text=ob_get_clean() ;
        $this->add_element('disk_info.HTML',$text) ;

    }

  function show_dir_info($title,$recs,$show_status)
  {   ?><h2><?echo $title?></h2><?
      $size=0 ; $count=0 ;
      ?><table class="basic fz_small full"><tr><th>Директория</th><th>Размер</th><th>Число файлов</th></tr><?
      if (_sizeof($recs)) foreach($recs as $rec)
         if ($rec['status']==$show_status)
         {?><tr><td class="left"><?echo $rec['obj_name']?></td>
                <td><?echo show_size($rec['size']) ; $size+=$rec['size'] ;?></td>
                <td><?echo $rec['cnt']; $count+=$rec['cnt'] ;?></td>
            </tr><?
         }
      ?><tr><th class="left">ИТОГО:</th><th><?echo show_size($size)?></th><th><?echo $count?></th></tr><?
      ?></table><br><?
  }

    function get_zip_term_logs() {
        ob_start();
        ?>
        <img id="load_gif" src="/images/loading15.gif" hidden>
        <?
        $html = ob_get_clean();
        $this->add_element('loading_layer.HTML', $html);

        include_once(_DIR_EXT.'/log/i_term_log.php') ;
        $rec_terminal = ESMO()->get_terminal_by_pkey($_POST['term_id']) ;

        $log_names = TERM_LOG()->get_term_log_names($rec_terminal['ip']);
        $archive_name = date('j_m_Y_h_i_s') . '_term_logs.zip';
        $archive_dir = '/temp/' . $archive_name;
        $zip = new ZipArchive();

        if ($zip->open(_DIR_TO_ROOT . $archive_dir, ZipArchive::CREATE) !== true) {
            $this->add_element('show_notife', 'error while creating archive file', ['color' => 'red']);
        }

        foreach ($log_names as $i) {
            $log = TERM_LOG()->get_log_from_url(_MAIN_PROTOCOL.$rec_terminal['ip'].':'._TERMINAL_PORT.'/log/'.$i); //TODO: htpps replace $_MAIN_PROTOCOL
            $zip->addFile($log, $i);
        }

        $zip->close();

        $this->go_url=_PATH_TO_SITE.$archive_dir ;
    }

    // получает и обрабатывает лог с терминала
    function get_term_log() {
        include_once(_DIR_EXT.'/log/i_term_log.php') ;

        ob_start();
        ?>
        <img id="load_gif" src="/images/loading15.gif" hidden>
        <?
        $html = ob_get_clean();
        $this->add_element('loading_layer.HTML', $html);

        $t_offset = TERM_LOG()->termd_time_offset;
        $rec_terminal = ESMO()->get_terminal_by_pkey($_POST['term_id']);
        $log_fname = TERM_LOG()->get_log_from_url(_MAIN_PROTOCOL.$rec_terminal['ip'].':'._TERMINAL_PORT.'/log/'.$_POST['filename'].'.log', $_POST['filename']); //TODO: поменять https на _MAIN_PROTOCOL, $rec_terminal['ip']

        if(!$log_fname) {
            $this->add_element('show_notife','Не удалось загрузить лог с терминала', ['color' => 'red']);
            return;
        }

        $json_log_fname = TERM_LOG()->process_log($log_fname, ['save_as_json' => 1]);

        if($_POST['cur_mo']) { // если
            $this->add_element('header.HTML', '');
            ob_start();
            TERM_LOG()->filter_log_data(['by_mo' => $_POST['cur_mo']]);
            if(!_sizeof(TERM_LOG()->log_content)) {
                $this->add_element('show_notife','Не удалось получить данные лога по текущему медосмотру', ['color' => 'red']);
                $this->add_element('show_log.HTML', '');
                return;
            }
            TERM_LOG()->print_log();
            $html = ob_get_clean();
            $this->add_element('show_log.HTML', $html);
        } elseif ($_POST['filename'] == 'terminald' and ($_POST['cur_mo_start'] and $_POST['cur_mo_end'])) {
            $this->add_element('header.HTML', '');

            ob_start();
            $ts_start = $_POST['cur_mo_start'] - $t_offset;
            $ts_end = $_POST['cur_mo_end'] + $t_offset;
            TERM_LOG()->filter_log_data(['by_timestamp' => ['start' => $ts_start, 'end' => $ts_end]]);
            if(!_sizeof(TERM_LOG()->log_content)) {
                $this->add_element('show_notife','Не удалось получить данные лога по текущему медосмотру', ['color' => 'red']);
                $this->add_element('show_log.HTML', '');
                return;
            }
            TERM_LOG()->print_log();
            $html = ob_get_clean();
            $this->add_element('show_log.HTML', $html);
        } else {
            ob_start();
//            echo $log_fname.'<br>';
            TERM_LOG()->print_log_header(basename($json_log_fname), ['mo_card_btn'=>1]);
            $html = ob_get_clean();
            $this->add_element('header.HTML', $html);

            $this->add_element('show_log.HTML', '');
        }
    }

    function get_content_for_date() {
        $ts_start = $_POST['start'];
        $ts_end = $_POST['end'];
        ob_start();
        ?>
        <img id="load_gif" src="/images/loading15.gif" hidden>
        <?
        $html = ob_get_clean();
        $this->add_element('loading_layer.HTML', $html);

//        damp_array($_POST);
//        $this->add_element('show_modal_window','HTML');

        include_once(_DIR_EXT.'/log/i_term_log.php') ;

        //, ['filter' => ['start_ts' => $ts_start, 'end' => $ts_end]]
        TERM_LOG()->process_json_file(_DIR_TO_ROOT . '/temp/' . $_POST['file']);
        TERM_LOG()->filter_log_data(['by_timestamp' => ['start' => $ts_start, 'end' => $ts_end]]);
        TERM_LOG()->collapse_repeats();

//        $content = TERM_LOG()->log_content;
        $stats = TERM_LOG()->log_stats['dates'][date('d-m-Y', $ts_start)];

        // отладка
//        ob_start();
//        echo $ts_start.'<br>';
//        echo $ts_end.'<br>';
//        damp_array($stats);
////        echo $_POST['file'];
//        $html = ob_get_clean();
//        $this->add_element('show_log.HTML', $html);

        ob_start();
//        damp_array($stats);
        // формеруем стат-ку для графика
        $stats_for_graf = [];
        foreach ($stats['hours'] as $hour => $val) {
            $hour .= ':00';
            $stats_for_graf[$hour] = [
                'errors' => $val['errors'],
                'mo_cnt' => $val['mo_cnt'],
//                'reboot_cnt' => $val['reboot_cnt']
            ];
        }
        TERM_LOG()->day_log_graf($stats_for_graf);

        if($_POST['mo_card_btn']) {
            TERM_LOG()->print_log(['mo_card_btn'=>1]);
        } else {
            TERM_LOG()->print_log();
        }

//        damp_array(TERM_LOG()->log_stats);

        $html = ob_get_clean();
        $this->add_element('show_log.HTML',$html) ;

        ob_start();
        TERM_LOG()->log_second_nav();
        $html = ob_get_clean();
        $this->add_element('log_second_nav.HTML',$html) ;

        $date = date('d-m-Y', $ts_start);
        $this->add_element('date-'.$date.'.CMD_REPLACE', 'log/reset_date') ;

        $this->add_element('JSCODE','<script type="text/javascript">$j("#date-'.$date.'").parent().siblings().children().attr("cmd", "log/get_content_for_date");</script>') ;
    }

    function reset_date() {
        ob_start();
        ?>
        <img id="load_gif" src="/images/loading15.gif" hidden>
        <?
        $html = ob_get_clean();
        $this->add_element('loading_layer.HTML', $html);

        include_once(_DIR_EXT.'/log/i_term_log.php') ;

        TERM_LOG()->process_json_file(_DIR_TO_ROOT . '/temp/' . $_POST['file']);

        $stats_for_graf = [];
        foreach (TERM_LOG()->log_stats['dates'] as $date => $val) {
            $stats_for_graf[$date] = [
                'errors' => $val['errors']['cnt'],
                'mo_cnt' => $val['mo']['cnt'],
                'reboot_cnt' => $val['reboot_cnt'],
            ];
        }

        ob_start();
        TERM_LOG()->log_graf($stats_for_graf);
        $html = ob_get_clean();
        $this->add_element('show_log.HTML',$html) ;
        $this->add_element('log_second_nav.HTML','<span class="log-nav_placeholder">Выберите дату</span>') ;
        $this->add_element('date-'.date('d-m-Y', $_POST['start']).'.CMD_REPLACE', 'log/get_content_for_date') ;

//        $this->add_element('JSCODE','<script type="text/javascript">$j("#date-'.$date.'").parent().siblings().children().attr("cmd", "log/get_content_for_date");</script>') ;
    }

    function log_json()
    { $theme=$_POST['theme'] ;
      $title=$_POST['title'] ;
      $text=$_POST['text'] ;
      $log_fname=$_POST['log_fname'] ;
      LOG_JSON($theme)->reg($title,$text) ;
      $reg_event=1 ;
      if ($log_fname)
	  { if (LOG_JSON($theme)->log_file_exists($log_fname)) $reg_event=0 ;
        // не выставлять reg_log в 1, если файл лога уже существует, соответствено запись в журнале событий уже есть
        // регистрацию надо сделать один раз, при первой записи в журнал, тогда ссылка на лог останетьися в журнале
        $log_fname=LOG_JSON($theme)->flush($log_fname,array('reg_log'=>$reg_event,'comment'=>$text)) ;
	  }
      $this->add_element('log_fname',$log_fname);
	}

    /*
  function reg_log()
 {   $reg_event=1 ;
     include_once(_DIR_TO_MODULES.'/engine/i_logs.php') ;
     LOG_JSON('debug_signature')->reg($_POST['t'],$_POST['text']) ;
     if (LOG_JSON('debug_signature')->log_file_exists('debug_signature_'.$_POST['uid'])) $reg_event=0 ;
     $log_fname=LOG_JSON('debug_signature')->flush('debug_signature_'.$_POST['uid']) ;
     if ($reg_event) LOGS()->reg_log('debug_signature','<a href="'.$log_fname.'" target="_blank">Лог</a>',array('account_id'=>MEMBER()->id)) ;
 }*/

    function cef_logs(){
        ob_start();
        LOGS()->cef_logs();
        $text = ob_get_clean();
        $this->add_element('cef_res.HTML',$text) ;
    }

    function clear_log_reg()
    {
        execSQL_update('truncate obj_site_req_log') ;
        $this->update_page=1 ;
    }

}
