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

   // получаем видео для прохода от check_access до pass
   function get_video_to_pass()
   { $rec_event=execSQL_van('select * from view_gate_events where pkey='.$_POST['evt_id']) ;
     //print_r($rec_event) ;
     if ($rec_event['evt_type']==2 and $rec_event['access_type']==1 and $rec_event['pass_type']==1) // ПРОХОД + ВЫХОД + РАЗОВЫЙ ПРОПУСК
     {      $rec_check_access=$rec_event;
            $time1_arr=getdate($rec_check_access['c_data']) ;
            $rec_check_access['c_data']=mktime($time1_arr['hours'],$time1_arr['minutes'],$time1_arr['seconds']-5,$time1_arr['mon'],$time1_arr['mday'],$time1_arr['year']);
            $rec_event['c_data']=mktime($time1_arr['hours'],$time1_arr['minutes'],$time1_arr['seconds']+15,$time1_arr['mon'],$time1_arr['mday'],$time1_arr['year']);
     }
     elseif ($rec_event['evt_type']==1) // АВТОРИЗАЦИЯ
     {
         $rec_check_access=$rec_event;
         $time1_arr=getdate($rec_check_access['c_data']) ;
         $rec_check_access['c_data']=mktime($time1_arr['hours'],$time1_arr['minutes'],$time1_arr['seconds']-10,$time1_arr['mon'],$time1_arr['mday'],$time1_arr['year']);
     }
     else // ПРОХОД
     {   // получаем
         $rec_check_access=execSQL_van('select * from view_gate_events where pass_type='.$rec_event['pass_type'].' and pass_id='.$rec_event['pass_id'].' and pkey<'.$rec_event['pkey'].' and evt_type=1 and result=1 order by pkey desc limit 1') ;

     }
     //  damp_array($rec_event,1,-1) ;
     $access_type=$rec_event['access_type'] ;
     $rec_terminal=SKD()->get_device_by_pkey($rec_event['device_id']) ;
      // damp_array($rec_terminal,1,-1) ;
     $stream_name='' ;
     if ($rec_terminal['stream_name_in'] and !$access_type)      $stream_name=$rec_terminal['stream_name_in'] ;
     elseif ($rec_terminal['stream_name_out'] and $access_type)  $stream_name=$rec_terminal['stream_name_out'] ;
     elseif ($rec_terminal['stream_name'])                       $stream_name=$rec_terminal['stream_name'] ;

     //$camera_uid=
     //echo '$access_type='.$access_type.'<br>' ;
     //echo 'stream_name_in='.$rec_terminal['stream_name_in'].'<br>' ;
     //echo 'stream_name_out='.$rec_terminal['stream_name_out'].'<br>' ;
     //echo 'stream_name='.$rec_terminal['stream_name'].'<br>' ;
     //echo '$stream_name='.$stream_name.'<br>' ;

     $_POST['time_from']=$rec_check_access['c_data'] ;
     $_POST['time_to']=$rec_event['c_data'] ;
     $_POST['stream']=$stream_name ;
     //echo 'check_access:'.date('d.m.Y H:i:s',$rec_check_access['c_data']).'<br>' ;
     //echo 'pass:'.date('d.m.Y H:i:s',$rec_event['c_data']).'<br>' ;
     //if ($stream_name)
     MEDIA_SERVER()->get_video_to_time() ;
   }


    function panel_mega_menu_item($url,$item,$i)
     {  if (!is_array($item))  $item=array('title'=>$item) ;
        if (is_int($url)) $url='' ;
        ?><li aria-haspopup="false" style="background: #bfc1c5; border-width: 1px; border-color: white;">
          	<a href="<?echo $url.$this->menu_url_params?>" class="modal_window_top_menu"
                    <? if (_sizeof($item)) foreach($item as $name=>$value) if ($name!='class' and $name!='title' and $name!='info_id')
                    { if ($name=='cmd') echo 'class=v2 cmd="'.$value.'"' ;
                      elseif ($name=='new_window') echo ' class="new_window" title="'.$value.'" ' ;
                      else              echo $name.'="'.$value.'"' ;
                    }
                    ?>><i class="<?echo $item['class']?>"></i><?echo $item['title']?></a>
            <?if ($item['info_id']){?><span class="info" id="<?echo $item['info_id']?>"></span><?}?>
            <?if (_sizeof($item['items'])){?><div class="grid-container4"><ul><?foreach($item['items'] as $url2=>$item2) $this->panel_mega_menu_item($url2,$item2);?></ul></div><?}?>
         </li>
       <?

     }

    function check_upload_file()
     {
        $video_name=$_POST['file_name'];
        $video_dir=_DIR_TO_ROOT.'/temp/'.$video_name ;
        $video_url=_MAIN_PROTOCOL._MAIN_DOMAIN.'/temp/'.$video_name ;
        if (!file_exists($video_dir)) $this->add_element('file_is_upload',0) ;
        else
        { $this->add_element('file_is_upload',1) ;
          ob_start() ;
            $this->player_code($video_url) ;
          $text=ob_get_clean() ;
          $this->add_element('player_code',$text) ;
        }
     }

   function player_code_avi($video_url,$options=array())
   {  $video_width=($options['video_width'])? $options['video_width']:400 ;
      $video_height=($options['video_height'])? $options['video_height']:300 ;
      //damp_array($options,1,-1) ;
       ?><br>
       <video controls width="<?echo $video_width?>" height="<?echo $video_height?>" <?if ($options['video_rotare']) echo 'style="transform:rotate('.$options['video_rotare'].'deg);"'?>>
         <source src="<?echo $video_url?>">
       </video>
       <div id="panel_filter" class="button_to_upload_video"><form id="sky-form" class="sky-form">
                 <a class="button" href="/services/get_video/?url=<? echo $video_url?>">Скачать</a>
              </form></div>
              <style type="text/css">
                  div#panel_filter.button_to_upload_video{text-align:center;}
                  div#panel_filter.button_to_upload_video p.info{margin:50px 100px 50px 100px;font-size:16px;}
                  div#panel_filter.button_to_upload_video a.button{float:none;margin:30px 100px 30px 100px;}
              </style>
       <?
   }
   function player_code($video_url)
   { // пока плейер не поддерживает AVI -  показываем только кнопку "скачать"
     ?><div id="panel_filter" class="button_to_upload_video"><form id="sky-form" class="sky-form">
          <p class="info">Вы можете сохранить видеофрагмент с терминала на свое рабочее место и посмотреть его с помощью установленного видеопроигрывателя</p>
          <a class="button" href="/services/get_video/?url=<? echo $video_url?>">Скачать</a>
       </form></div>
       <style type="text/css">
           div#panel_filter.button_to_upload_video{text-align:center;}
           div#panel_filter.button_to_upload_video p.info{margin:50px 100px 50px 100px;font-size:16px;}
           div#panel_filter.button_to_upload_video a.button{float:none;margin:30px 100px 30px 100px;}
       </style>
      <?
      return ;
      echo $video_url ;
      $this->player_code_avi($video_url) ; return ;
     $id=rand(1,1000000000) ;
     ?><div style="float:right;margin:10px 20px 10px 0;"><a href="/services/get_video/?url=<? echo $video_url?>">Скачать</a></div>
       <div class="clear"></div>
       <div id="myElement_<?echo $id?>"></div>
       <script type="text/javascript">$j(document).ready(function()
       {   var playerInstance_<?echo $id?> = jwplayer("myElement_<?echo $id?>");
           playerInstance_<?echo $id?>.setup({
              //image: "/uploads/myPoster.jpg",
              file: "<?echo $video_url?>",
              key:"lHm9KBKfyMLaBzg7wRAqWVtDJBPMrRgxAtd0DA==",
              autostart: true,
              //stretching:"exactfit",
              height: "500",
              width: "700"
            });
       }) ;
       </script>
     <?
   }

    function get_video_from_terminal() {
        $video_options=[] ;
        if ($_POST['id_mo']) $rec_mo=ESMO()->get_mo_by_id($_POST['id_mo']) ;
        if ($_POST['id_kt']) {
            $rec_mo=KT()->get_mo_by_id($_POST['id_kt']) ;
            $video_options=array('video_rotare'=>270,'video_width'=>400,'video_height'=>400) ;
        }
        $rec_terminal=ESMO()->get_terminal_by_id($rec_mo['terminal_id']) ;

        $arhive_file_name=_DIR_TO_ROOT.'/capture/'.$rec_mo['pkey'].'.webm' ;
        $arhive_file_url=_MAIN_PROTOCOL._MAIN_DOMAIN.'/capture/'.$rec_mo['pkey'].'.webm' ;

        // описываем меню
        if ($rec_terminal['stream_name_1']) $this->second_menu['/camera_ext_1/']=array('title'=>'Камера № 1','get_type'=>'menu_panel_ext_1') ;
        if ($rec_terminal['stream_name_2']) $this->second_menu['/camera_ext_2/']=array('title'=>'Камера № 2','get_type'=>'menu_panel_ext_2') ;
        if (file_exists($arhive_file_name)) $this->second_menu['/arhiv/']=array('title'=>'Архив видео','get_type'=>'terminal_video_from_archive') ;
        else if ($rec_mo['video']) $this->second_menu['/camera_int_1/']=array('title'=>'Камера терминала','get_type'=>'terminal_video') ;
        if ($GLOBALS['LS_trassir_enable']) {
            $this->second_menu['/camera_trassir/']=array('title'=>'Разбор инцидентов','get_type'=>'trassir') ;
        }

        // формируем меню
        $i=0 ;
        ?>
        <ul id=panel_second_menu class="modal_box sky-mega-menu sky-mega-menu-response-to-icons sky-mega-menu-anim-scale">
            <?if (_sizeof($this->second_menu)) foreach($this->second_menu as $url=>$item) { $this->panel_mega_menu_item($url,$item,$i) ; $i++ ; }?>
        </ul>
        <div class=clear></div>
        <div id="tab_panels">Выберите источник видео</div>

        <style type="text/css">
            div#tab_panels{text-align:center;min-height:350px;}
        </style>
        <script type="text/javascript">
        // скрипт для управления панелями
        $j('a.modal_window_top_menu').click(function() {
            var id=$j(this).attr('panel');
            $j('ul#panel_second_menu.modal_box li').removeClass('current');
            $j(this).closest('li').addClass('current');
            let getAttr = $j(this).attr('get_type') ;
            console.log(getAttr);
            switch (getAttr) {
                case 'trassir':
                    send_ajax_request({cmd:'media_server/get_trassir_panel'<?if ($_POST['id_mo'])  echo ',id_mo:'.$_POST['id_mo']?>});
                    break;
                case 'terminal_video':
                    send_ajax_request({cmd:'media_server/get_terminal_video_panel'<?if ($_POST['id_mo'])  echo ',id_mo:'.$_POST['id_mo']?>,<?if ($_POST['id_kt']) echo 'id_kt:'.$_POST['id_kt']?>});
                    break;
                case 'terminal_video_from_archive':
                    console.log('terminal_video_from_archive');
                    send_ajax_request({cmd:'media_server/get_terminal_video_archive_panel'<?if ($_POST['id_mo'])  echo ',id_mo:'.$_POST['id_mo']?>,arhive_file_url:<?echo "'".$arhive_file_url."'"?><?if ($_POST['id_kt']) echo ',id_kt:'.$_POST['id_kt']?>});
                    break;
            }
            return(false) ;
        }) ;

        $j('div#tab_panels div.panel').hide() ;
        $j('div#tab_panels div.panel:first-child').show() ;

        function stop_video_capture() {
          <?
          if ($GLOBALS['LS_trassir_enable']) {
              ?>
              if (typeof hls != "undefined") {
                    $j("body").stopTime('check_video_length')
                    hls.stopLoad()
                    hls.detachMedia()
                    delete(hls)
              }
              <?
          }
          ?>
        }
        </script>
        <?

        $this->add_element('show_modal_window','HTML',array('title'=>'MО '.$rec_mo['pkey'].', '.$rec_mo['member_name'],'width'=>'700px','after_close_func'=>'stop_video_capture')) ;
    }

    function get_trassir_panel() {
       if ($_POST['id_mo']) {
           $rec_mo=execSQL_van('select * from view_mo_session where pkey='.$_POST['id_mo']) ;
           if ($rec_mo['terminal_id']) $rec_terminal=ESMO()->get_terminal_by_id($rec_mo['terminal_id']) ;
           ob_start();

           $terminal_cameras=[]; $group_cameras=[]; $error='';
           if ($rec_mo['hand_check_user_id']) {
                $medic_hand_check_cameras=execSQL('select camera_trassir_id from obj_site_trassir_camera_terminal where hand_check_group_id='.$rec_mo['group_id']);
                if (!_sizeof($medic_hand_check_cameras)) {
                       $error='РМВ не указаны камеры Trassir';
                } else {
                      $cameras=$medic_hand_check_cameras;
                }
           } else {
                $terminal_cameras=execSQL('select camera_trassir_id from obj_site_trassir_camera_terminal where terminal_id='.$rec_terminal['pkey']);
                if (!_sizeof($terminal_cameras)) {
                    $group_cameras=execSQL('select camera_trassir_id from obj_site_trassir_camera_terminal where group_id='.$rec_terminal['parent']);
                    if (!_sizeof($group_cameras)) {
                       $error='Для терминала и группы не указаны камеры Trassir';
                    } else {
                      $cameras=$group_cameras;
                    }
                } else {
                    $cameras=$terminal_cameras;
                }
           }

           if ($error) {
                echo $error;
           } else {
                $camera_recs=execSQL('select guid,obj_name from obj_site_trassir_channels where pkey in ('.implode(',',array_keys($cameras)).')',0,1);
                $params['time_from']=$rec_mo['c_data'] ;
                $hours=3;
                $time_from=$params['time_from'];
                $time1_arr=getdate($time_from) ;
                if ($rec_mo['hand_check_user_id']) {
                    $time_from=mktime($time1_arr['hours']+$GLOBALS['LS_trassir_time_offset'],$time1_arr['minutes'],$time1_arr['seconds']-$GLOBALS['LS_trassir_time_before_hand_ME'],$time1_arr['mon'],$time1_arr['mday'],$time1_arr['year']);
                    $mo_length=$rec_mo['e_data']-$rec_mo['c_data']+$GLOBALS['LS_trassir_time_before_hand_ME']+$GLOBALS['LS_trassir_time_after_hand_ME'];
                } else {
                    $time_from=mktime($time1_arr['hours']+$GLOBALS['LS_trassir_time_offset'],$time1_arr['minutes'],$time1_arr['seconds']-$GLOBALS['LS_trassir_time_before_ME'],$time1_arr['mon'],$time1_arr['mday'],$time1_arr['year']);
                    $mo_length=$rec_mo['e_data']-$rec_mo['c_data']+$GLOBALS['LS_trassir_time_before_ME']+$GLOBALS['LS_trassir_time_after_ME'];
                }

                $time_from=$time_from.'000000';
                ?>
                <div class="trassir_chanels">
                <?
                foreach ($camera_recs as $camera_rec) {
                    ?>
                    <button id="<?echo $camera_rec['guid']?>" onclick="send_ajax_request({cmd:'media_server/trassir_get_cam_video',trassir_guid:'<?echo $camera_rec['guid']?>',trassir_timestamp:'<?echo $time_from?>',video_length:'<?echo $mo_length?>'})"><?echo $camera_rec['obj_name']?></button>
                    <?
                }
                ?>
                </div>
                <div id="test_trassir_text"></div>
<!--                <video id="video_trassir" controls></video>-->
                <script src="/AddOns/video-dev/hls.js"></script>
                <script type="text/javascript">
                    // $j(document).ready(function() {
                        send_ajax_request({cmd:'media_server/trassir_get_cam_video',trassir_guid:'<?echo $camera_recs[0]['guid']?>',trassir_timestamp:'<?echo $time_from?>',video_length:'<?echo $mo_length?>'})
                    // })
                </script>
                <style type="text/css">
                    div.trassir_chanels {padding: 10px;}
                    #video_trassir {height:350px;}
                </style>
                <?
           }
           $HTML=ob_get_clean();
           $this->add_element('tab_panels.HTML', $HTML) ;
       }
    }

    function get_terminal_video_panel() {
        $video_options=[] ;
        if ($_POST['id_mo']) $rec_mo=execSQL_van('select * from view_mo_session where pkey='.$_POST['id_mo']) ;
        if ($_POST['id_kt']) {
            $rec_mo=KT()->get_mo_by_id($_POST['id_kt']) ;
            $video_options=array('video_rotare'=>90,'video_width'=>400,'video_height'=>400) ;
        }
        if ($rec_mo['pkey']) {
            if ($rec_mo['terminal_id']) $rec_terminal=device()->get_terminal_by_id($rec_mo['terminal_id']) ;
            ob_start();

            $video_name=basename($rec_mo['video']) ;
            $video_dir=_DIR_TO_ROOT.'/temp/'.$video_name ;
            $video_url=_MAIN_PROTOCOL._MAIN_DOMAIN.'/temp/'.$video_name ;

            // unlink($video_dir) ;

            if (file_exists($video_dir) and filesize($video_dir)>0) $this->player_code_avi($video_url,$video_options) ;
            else { // пытаемся получить файл с файлового хранилища
                $from=$GLOBALS['LS_url_video_arhive'] ;
                $to=_DIR_TO_ROOT.'/temp/' ;
                $doc_name=$to.$rec_mo['video'] ;
                $video_fname=basename($rec_mo['video']) ;
                $res=IO()->doPut_v2(_MAIN_PROTOCOL,$GLOBALS['LS_url_video_arhive'],'/'.$video_fname,'','',['save_content_to_file'=>_TEMP_DIR.$video_fname]) ;
                if ($res['status']==200) {
                    //damp_array($res) ;
                    $this->player_code_avi($video_url,$video_options) ;
                } else {
                    if (file_exists($video_dir)) unlink($video_dir) ;
                    ob_start() ;
                    $log_uid=rand(1,10000000)  ;
                    $from=$rec_terminal['ip'].':'.$rec_mo['video'] ;
                    $to=_DIR_TO_ROOT.'/temp/' ;
                    $doc_name=$to.$rec_mo['video'] ;
                    $video_fname=basename($rec_mo['video']) ;

                    $cmd='/usr/bin/wget --timeout=2 --tries=1  --no-check-certificate -O '._TEMP_DIR.$video_fname.' '._MAIN_PROTOCOL.$rec_terminal['ip'].':'._TERMINAL_PORT.'/data/'.$video_fname ;
                    $outputfile='log_'.$log_uid.'.txt' ;      // echo '$outputfile='.$outputfile.'<br>' ;
                    $pidfile='exec_'.$log_uid.'.txt' ;          //    echo '$pidfile='.$pidfile.'<br>' ;
                    if (file_exists(_TEMP_DIR.$outputfile)) unlink(_TEMP_DIR.$outputfile) ;
                    if (file_exists(_TEMP_DIR.$pidfile)) unlink(_TEMP_DIR.$pidfile) ;
                    $cmd=sprintf("%s > '%s' 2>&1 & echo $! >> '%s'", $cmd, _TEMP_DIR.$outputfile, _TEMP_DIR.$pidfile) ;  // echo 'cmd='.$cmd.'<br>' ;
                    exec($cmd)   ;
                    $cont=file_get_contents(_TEMP_DIR.$outputfile) ;
                    echo $cont ;
                    $text=ob_get_clean()  ;
                    echo $text ;
                    LOGS()->reg_log('get_file_by_scp',$text.'<br><a href="'._TEMP_PATH.$doc_name.'" target=_blank>'.$doc_name.'</a><br><a href="'._TEMP_PATH.$outputfile.'" target=_blank>'.$outputfile.'</a><br><a href="'._TEMP_PATH.$pidfile.'" target=_blank>'.$pidfile.'</a><br>') ;

                    ?><div id="log_view"></div>
                    <style type="text/css">#log_view{height:400px;overflow-y: scroll;margin-bottom:15px;border-top:1px solid #dddddd;border-left:1px solid #dddddd;border-bottom:1px solid #dddddd;padding:10px 0 10px 10px;</style>
                    <script type="text/javascript">
                    var panel_messages=$j('#log_view') ;
                    $j('body').everyTime(1000,'update_log_view',function()
                    {  send_ajax_request({cmd:'media_server/update_log_view',cmd_uid:'<?echo $log_uid?>',file_name:'<?echo $video_fname?>'<?if ($_POST['id_kt']) echo ',video_rotate:1'?>}) ;
                    //console.log(panel_messages[0].scrollHeight+' - '+panel_messages[0].clientHeight);
                    // scroll animate небходимо переставить в функцию, которая выводит текст, сейчас анимация опазывает за выводом
                    panel_messages.animate({scrollTop:panel_messages[0].scrollHeight-panel_messages[0].clientHeight+20});
                    });
                    </script>
                    <?
                }
            }

            $HTML=ob_get_clean();
            $this->add_element('tab_panels.HTML', $HTML) ;
        }
    }

    function get_terminal_video_archive_panel() {
        $video_options=[] ;
        if ($_POST['id_kt']) {
            $video_options=array('video_rotare'=>90,'video_width'=>400,'video_height'=>400) ;
        }
        if ($_POST['arhive_file_url']) {
            $video_url=$_POST['arhive_file_url'];
            ob_start();

            $video_width=($video_options['video_width'])? $video_options['video_width']:400 ;
            $video_height=($video_options['video_height'])? $video_options['video_height']:300 ;
            //damp_array($options,1,-1) ;
            ?><br>
            <video controls width="<?echo $video_width?>" height="<?echo $video_height?>" <?if ($video_options['video_rotare']) echo 'style="transform:rotate('.$video_options['video_rotare'].'deg);"'?>>
            <source src="<?echo $video_url?>">
            </video>
            <div id="panel_filter" class="button_to_upload_video">
                <form id="sky-form" class="sky-form">
                <a class="button" href="/services/get_video/?url=<? echo $video_url?>">Скачать</a>
                </form>
            </div>
            <style type="text/css">
                div#panel_filter.button_to_upload_video{text-align:center;}
                div#panel_filter.button_to_upload_video p.info{margin:50px 100px 50px 100px;font-size:16px;}
                div#panel_filter.button_to_upload_video a.button{float:none;margin:30px 100px 30px 100px;}
            </style>
            <?

            $HTML=ob_get_clean();
            $this->add_element('tab_panels.HTML', $HTML) ;
        }
    }
   // получаем видео для MO
   // передаем параметр id_mo
   //

    function trassir_get_cam_video() {
       ob_start();
       if ($_POST['trassir_guid'] and $_POST['trassir_timestamp']) {
           $URL=$GLOBALS['LS_trassir_url'].'/api/v1/trassir/archive/'.$_POST['trassir_guid'].'/'.$_POST['trassir_timestamp'];
            $ch = curl_init($URL);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $json = '';
            if( ($json = curl_exec($ch) ) !== false)
            {
                $response_arr=json_decode($json,true);
                if (_sizeof($response_arr) and $response_arr['playlist']) {
                    $url_stream=$response_arr['playlist'];
                    ?>
                    <video id="video_trassir" controls></video>
                    <script type="text/javascript">
                        var video_length = <?echo $_POST['video_length'];?>

                        if (typeof hls != "undefined") {
                            $j("body").stopTime('check_video_length')
                            hls.stopLoad()
                            hls.detachMedia()
                            delete(hls)
                        }
                        var hls = new Hls()
                        $j(document).ready(function() {
                            var video = document.getElementById('video_trassir')
                            if(Hls.isSupported()) {

                                hls.loadSource('<?echo $url_stream?>')
                                hls.attachMedia(video)
                                hls.on(Hls.Events.MANIFEST_PARSED,function() {
                                    console.log('MANIFEST_PARSED')
                                    video.play()
                                });

                                hls.on(Hls.Events.ERROR, function (event,data) {

                                    console.log()
                                    var errorType = data.type
                                    var errorDetails = data.details
                                    var errorFatal = data.fatal

                                    console.log(errorType, errorDetails, errorFatal)
                                });
                                <?
                                if ($_POST['video_length']) {
                                    ?>
                                    $j('body').everyTime(1000,'check_video_length',function(){
                                        if ((hls.media.duration>=video_length) && (hls.media.currentTime>=video_length)) {
                                            hls.stopLoad()
                                        }
                                        if (hls.media.currentTime>=video_length) {
                                            hls.media.currentTime=0
                                        }
                                    })
                                    <?
                                }
                                ?>
                            }
                        });
                    </script>
                    <?
                } else {
                    ?>

                    <?
                }
            }
       }
       $html=ob_get_clean();
       $this->add_element('test_trassir_text.HTML', $html) ;
    }


   function get_video()
   {

   }


    function update_log_view()
  {   $outputfile='log_'.$_POST['cmd_uid'].'.txt' ;
      if (file_exists(_TEMP_DIR.$outputfile)) $text=file_get_contents(_TEMP_DIR.$outputfile) ;
      else                                    $text='Не найден лог подготовки документа <strong>'.$outputfile.'</strong><br>' ;

	  $arr=explode(chr(10),$text) ;
	  $last_line=$arr[_sizeof($arr)-2] ;

      $this->add_element('log_view.HTML','<div style="margin-top:150px;font-size:16px;color:green;">Ожидайте, идет загрузка видеофайла</div><div style="font-size:20px;color:#272727;margin-top:20px;">'.$last_line.'</div>') ;
      if (strpos($text,'404 Not Found')!==false)
      { $this->add_element('JSCODE','<script type="text/javascript">$j("body").stopTime("update_log_view");</script>') ;
        $this->add_element('tab_panels.HTML','<div style="font-size:20px;color:red;margin-top:50px;">Видео удалено с терминала</div><br><div class="comment">Срок хранения видео на терминале - 3 дня</div>') ;
      }

      if (strpos($text,'Done')!==false or strpos($text,'100%')!==false or strpos($text,'saved')!==false)
      { $this->add_element('JSCODE','<script type="text/javascript">$j("body").stopTime("update_log_view");</script>') ;
        ob_start() ;
        $video_name=$_POST['file_name'];
        $video_url=_MAIN_PROTOCOL._MAIN_DOMAIN.'/temp/'.$video_name ;
        $video_options=[];
        if ($_POST['video_rotate']) $video_options=array('video_rotare'=>90,'video_width'=>400,'video_height'=>400) ;
        $this->player_code_avi($video_url,$video_options) ;
        $text=ob_get_clean() ;
        $this->add_element('tab_panels.HTML',$text) ;
      }

  }


   function panel_player_video_from_media_server($rec_mo,$rec_terminal,$stream_num=1)
   {
     $params['time_from']=$rec_mo['c_data'] ;
     $params['time_to']=$rec_mo['e_data'] ;
     $params['VS_IP']=$rec_terminal['VS_IP'] ;
     $params['stream']=$rec_terminal['stream_name_'.$stream_num] ;
     $hours=-3 ;
     $arr['Время МО, местное']=date('Y-m-d H:i:s',$rec_mo['c_data']).' - '.date('H:i:s',$rec_mo['e_data']) ;
     $arr['Смещение, час']=$hours ;

       //damp_array($params) ;
          if (!isset($params['time_from'])) $params['time_from']=$params['time']-60 ;
          if (!isset($params['time_to']))   $params['time_to']=$params['time']+60 ;
          if (!isset($params['time']))      $params['time']=$params['time_from'] ;
          $time=$params['time'] ;
          $time_from=$params['time_from'] ;
          $time_to=$params['time_to'] ;


         //$arr['Коррекция']='2:10' ;


         $time1_arr=getdate($time_from) ;
         $time2_arr=getdate($time_to) ;
         $time_from=mktime($time1_arr['hours']+$hours,$time1_arr['minutes'],$time1_arr['seconds'],$time1_arr['mon'],$time1_arr['mday'],$time1_arr['year']);
         $time_to=mktime($time2_arr['hours']+$hours,$time2_arr['minutes'],$time2_arr['seconds'],$time2_arr['mon'],$time2_arr['mday'],$time2_arr['year']);



          // готовим строку запроса
          $var = array();
          $var['date'] = date('Y-m-d H:i:s');
          $var['operation'] = 'record';
          $var['args']['range']['date_start']=date('Y-m-d H:i:s',$time_from) ;
          //$var['args']['range']['date_start']=gmdate('Y-m-d H:i:s',$time_from) ;
          //$var['args']['range']['date_end']=gmdate('Y-m-d H:i:s',$time_to) ;
          $var['args']['range']['date_end']=NULL ;
          $var['args']['camera']=$params['stream'] ;

          $video_server_ip=($params['VS_IP'])? $params['VS_IP']:_VIDEO_SERVER_IP ;

         //{ "operation": "record", args: {"range": {"date_start": дата, "date_end": дата}},camera: id камеры}}


          //$arr['Время события']=date('Y-m-d H:i:s',$time) ;
          //$arr['Время события (гринвич)']=gmdate('Y-m-d H:i:s',$time) ;
          //$arr['Запрос время ']=date('Y-m-d H:i:s',$time_from).' - '.date('H:i:s',$time_to) ;
          //damp_array($var,1,-1) ;

          //$var=array('test'=>123) ;
          $text_json=json_encode($var) ; //damp_string($text_json) ;

          LOGS()->reg_log('get_video_to_time',_MAIN_PROTOCOL.$video_server_ip.'/operation=record',array('data'=>$var)) ;

          $res=array();
          $result=IO()->doPut_v2(_MAIN_PROTOCOL,$video_server_ip,'/','operation=record',$text_json,array('no_log_request'=>1)) ;
          if ($result['status']==200) $res=json_decode($result['content'],true);

           /*?><h2>Получено с сервера</h2><?*/
           //damp_array($res,1,-1) ;
           //print_r($res) ;

          //$arr['Ответ время начало (гринвич)']=$res['records'][0]['start'] ;
          //$arr['Ответ время окончание (гринвич)']=$res['records'][0]['end'] ;

          //damp_array($arr,1,-1) ;

          if (!_sizeof($res['records']))
          { $this->add_element('show_notife','Видео не обнаружено',array('color'=>'red')) ;
            damp_array($arr,1,-1) ;
            ?><h2>Отправлено на сервер <?echo $video_server_ip?></h2><?
            damp_array($var,1,-1) ;
            ?><h2>Получено с сервера</h2><?
            //damp_array($res,1,-1) ;
          }
          else
          {   //damp_array($res,1,-1) ;
              $time_start=strtotime($res['records'][0]['start']) ;
              $time_end=strtotime($res['records'][0]['end']) ;

              $time1_arr=getdate($time_start) ;
              $time2_arr=getdate($time_end) ;
              //damp_array($time1_arr,1,-1) ;
              $time_start=mktime($time1_arr['hours'],$time1_arr['minutes'],$time1_arr['seconds'],$time1_arr['mon'],$time1_arr['mday'],$time1_arr['year']);
              $time_end=mktime($time2_arr['hours'],$time2_arr['minutes'],$time2_arr['seconds'],$time2_arr['mon'],$time2_arr['mday'],$time2_arr['year']);

              /*?><h2>Получено с сервера</h2><?
              damp_array($res,1,-1) ;*/


              $arr['Время ролика по серверу']=date('Y-m-d H:i:s',$time_start).' - '.date('H:i:s',$time_end)  ;

              //$time_start_k=mktime($time1_arr['hours']+3,$time1_arr['minutes']-2,$time1_arr['seconds']-10,$time1_arr['mon'],$time1_arr['mday'],$time1_arr['year']);
              //$time_end_k=mktime($time2_arr['hours']+3,$time2_arr['minutes']-2,$time2_arr['seconds']-10,$time2_arr['mon'],$time2_arr['mday'],$time2_arr['year']);
              //$arr['Время ролика коррекция']=date('Y-m-d H:i:s',$time_start_k).' - '.date('H:i:s',$time_end_k)  ;
              $arr['Название файла']=basename($res['records'][0]['url'])  ;

              // время по серверу - 15:21
              // время по медиасерверу -

              $int_before=($GLOBALS['LS_video_preview_from'])? $GLOBALS['LS_video_preview_from']:5 ;
              $int_after=($GLOBALS['LS_video_preview_after'])? $GLOBALS['LS_video_preview_after']:5 ; ;
              //echo '$time_from: '.date('d.m.Y H:i:s',$time_from).'<br>' ;
              //echo '$time_start: '.date('d.m.Y H:i:s',$time_start).'<br>' ;
              $offset1=$time_from-$time_start-$int_before ;
              //echo '$offset1: '.$offset1.'<br>' ;
              if ($offset1<0) $offset1=0 ;
              $offset2=$time_to-$time_start+$int_after ;
              //echo '$offset2: '.$offset2.'<br>' ;
              $len=$time_end-$time_start ;
              if ($offset2>$len) $offset2=$len ;
              //echo '$len: '.$len.'<br>' ;
              $arr['Время фрагмента']=floor($offset1/60).':'.($offset1 % 60).' - '.floor($offset2/60).':'.($offset2 % 60) ;

              //damp_array($arr,1,-1) ;
              $id=rand(1,1000000000) ;
              $center=0 ;
              //echo '$offset1='.$offset1.'<br>' ; echo '$offset2='.$offset2.'<br>' ; echo '$center='.$center.'<br>' ; echo '$k='.$k.'<br>' ;
              ?><div style="float:right;margin:10px 20px 10px 0;"><a href="/services/get_video/?url=<? echo rawurlencode($res['records'][0]['url'])?>">Скачать</a></div>
                <div style="float:right;margin:10px 20px 10px 0;"><a href="<? echo ($res['records'][0]['url'])?>" target="_blank">Открыть в браузере</a></div>
                <div style="float:left;margin:10px 0 10px 20px;" id="time_info1_<?echo $id?>">Время МО: <strong><?echo date('d.m.Y H:i:s',$time)?></strong></div>
                <div class="clear"></div>
                <div id="myElement_<?echo $id?>"></div>
               <script type="text/javascript">
                var playerInstance_<?echo $id?> = jwplayer("myElement_<?echo $id?>");
                playerInstance_<?echo $id?>.setup({
                   //image: "/uploads/myPoster.jpg",
                   file: "<?echo $res['records'][0]['url']?>",
                   key:"lHm9KBKfyMLaBzg7wRAqWVtDJBPMrRgxAtd0DA==",
                   autostart: true,
                   //stretching:"exactfit",
                   height: "500",
                   width: "700",

                 });

                playerInstance_<?echo $id?>.on('ready', function() {  playerInstance_<?echo $id?>.seek(<?echo $offset1?>);});

                playerInstance_<?echo $id?>.on('time', function(e)
                {   if (e.position><?echo $offset2?>) playerInstance_<?echo $id?>.seek(<?echo $offset1?>) ;
                    var date = new Date((<?echo $time_start?>+e.position)*1000);
                    var timestamp = <?echo $time_start?>+e.position-(date.getTimezoneOffset()-120)*60;
                    var date = new Date(timestamp*1000);
                    var iso = date.toISOString().match(/(\d{2}:\d{2}:\d{2})/) ;
                    $j('#time_info2_<?echo $id?> strong').html(iso[1]);
                });

               </script>
           <?
     }


    }

    function update_trassir_cameras_list() {
              if ($GLOBALS['LS_trassir_enable']) {
                  if ($GLOBALS['LS_trassir_url']) {
                    $json = file_get_contents($GLOBALS['LS_trassir_url'].'/api/v1/trassir/channels');
                    $channels=json_decode($json,true);
//                    damp_array($channels);
                    if (_sizeof($channels)) {
                        if ($channels['channels']) {
                            $exist_cameras=execSQL('select guid,obj_name,pkey from obj_site_trassir_channels');
                            foreach ($channels['channels'] as $channel) {
                                if (!_sizeof($exist_cameras[$channel['guid']])) {
                                    adding_rec_to_table('obj_site_trassir_channels',['guid'=>$channel['guid'],'obj_name'=>$channel['name'],'data'=>serialize($channel)]);
                                } else {
                                    update_rec_in_table('obj_site_trassir_channels',['obj_name'=>$channel['name'],'data'=>serialize($channel)],'pkey='.$exist_cameras[$channel['guid']]['pkey']);
                                }
                            }
                        }
                        $this->update_page=1;
                    }
                  } else {
                      $this->add_element('show_notife','Не указан URL Trassir Gateway',array('color'=>'red')) ;
                  }
              } else {
                  $this->add_element('show_notife','Не активировано использование Trassir',array('color'=>'red')) ;
              }
    }

}
