<?php

require __DIR__ . '/fb_tools.php';

//require __DIR__ . '/../../demosettings.php'; //also includes demosettings
/**
 * @param $argv
 * @return bool
 */  
function get_fb_data($argv){
    $data_set_name = !empty($argv[2]) ? $argv[2] : FB_DEFAULTS["data_set"]; // e.g. egypt-1
    $file_format = !empty($argv[3]) ? $argv[3] : FB_DEFAULTS["file_format"]; // e.g. file
    $start_entity_type = !empty ($argv[4]) ? $argv[4] :null;  // e.g. page
    $end_entity_type = !empty($argv[5]) ? $argv[5] : null; // e.g. comment
    $project_name =  !empty($argv[6]) ? $argv[6] :  FB_DEFAULTS["project_name"]; // e.g. beara
    $file_extension = !empty($argv[7]) ? $argv[7] : FB_DEFAULTS["file_extension"];   // e.g. txt
    
    
    $start_label = !empty($argv[4])? $argv[4] : "input";
    $end_label = !empty($argv[5]) ? $argv[5] : "output";
    
    echo "Fetching '" . $end_label . "' data from '" . $start_label . "' data (data set: '" . $data_set_name . "' of type '" . $file_format . "').\n\n"; 

    $data_set = fb_load_data_set($project_name, $data_set_name, $file_extension, $file_format);
    $data_arr = strip_entities_from_urls($data_set);
    if (empty($start_entity_type)) {
        $start_entity_type = fb_determine_entity_type($start_entity_type, $data_arr, "start");
    }
    if (empty($end_entity_type)) {
        $end_entity_type = fb_determine_entity_type($end_entity_type, $data_arr, "end");
    }
    $connection = NULL;
    $timestamp = date("Y-m-d-H");
    $folderName= $timestamp . "_" . $data_set_name;
    $res = fb_process_list($data_arr, $start_entity_type, $end_entity_type, $connection, null, $project_name, $data_set_name,$folderName);
    add_ToFolderListAnalysis($folderName);
    return $res;
}


function isItTimeToRunFbCrawler($runTime){
    if(empty($runTime)){
        return true;    
    }    
    while(true){
       $time = date('h:i a', time());
       echo "current time:".$time."\n";
       echo "runtime:".$runTime."\n";
       if($time == $runTime){
            echo "it is time to run crawler";    
           return true;
       }
       sleep(59);
    }
}

/* every day at given time 
 * this function download data from fb 
 * to run this  cd /cygdrive/c/xampp/htdocs/allInOneWeb/tools/cowitter/  
 * and the past this:
 * /cygdrive/c/xampp/php/php.exe cli_runner.php get_facebook_data_auto spain file page comment redalert txt "05:00 am"
 */
function get_fb_data_auto($argv){
    while(true){
        $runTime = !empty($argv[8]) ? $argv[8] : FB_DEFAULTS["timeOfCollectFbData"]; 
        $itIsTime = isItTimeToRunFbCrawler($runTime);

        if($itIsTime){
            $start_time = time();
            echo "Starting crawling facebook data";    
            try {
                get_fb_data($argv, 'stream_handler_function_all');
            } catch (Exception $e) {
                echo "crawler unexpectedly broke with message: " . $e->getMessage();
            } finally {
                $end_time = time() - $start_time;
                echo "\n  get_fb_data resigned after $end_time seconds! wait for a minute\n";
                sleep(61) === 0 or die("\nCould not go to sleep\n");
            }
        }    
   }
}


/* every day at given time 
 * copy data ivProjects-docs
 * keep folder name at sql table fb_folder_for_analysis
 * && uploads and analyze folder
 * to run this  cd /cygdrive/c/xampp/htdocs/allInOneWeb/tools/cowitter/  
 * and the past this:
 * /cygdrive/c/xampp/php/php.exe cli_runner.php analyze_facebook_data_auto redalert "07:00 am"
 * or without time to run just for once
 */
function analyze_facebook_data_auto($argv){
    while(true){
        $runTime = !empty($argv[3]) ? $argv[3] :null; 
        global $CURRENT_SOURCE_FOLDER;
        $folder = $argv[2];//folder of project
        $errorlevels = [];


        //$from = $CURRENT_SOURCE_FOLDER."\\tools\\fb_crawler\output_data\\".$folder;

       // echo "CURRENT_SOURCE_FOLDER:".$CURRENT_SOURCE_FOLDER."\n";
       // echo "folder".$folder."\n";
        //echo "from:".$from."\n";

        $itIsTime = isItTimeToRunFbCrawler($runTime);

        if($itIsTime || $runTime == NULL){
            $start_time = time();
            echo "Starting perform uploadFolder of facbook data\n";  
            try{
              performUploadFolder($errorlevels);  
            } catch (Exception $ex) {
                echo "crawler unexpectedly broke with message: " . $ex->getMessage();
            } finally {
                $end_time = time() - $start_time;
                echo "\n  analyze_facebook_data_auto resigned after $end_time seconds! wait for a minute\n";
                sleep(61) === 0 or die("\nCould not go to sleep\n");
            }

        }
   }
}

function performUploadFolder(&$errorlevels)
{ 
    global $sharedFolder;
    $dir_path = "$sharedFolder/docs/";
    $foldersList = get_all_folderListToAnalysis();
    $docFolderList = docTextFoldersList();
    
    
    foreach ($foldersList as $folder){   
        $isfolderExists= isFolderInDocText($folder,$docFolderList);
        if($isfolderExists){
              $errorlevels[] = asyncRequst::getInstance()->runPhpPage("tools/cowitter/autoSendFolder.php", [$folder], false);

           
            //eq. require tools/cowitter/autoSendFolder.php
            delete_FolderListAnalysis($folder);
        }
    }
}


function isFolderInDocText($folderName,$docFolderList){
    if(empty($docFolderList[$folderName])){
      return false;  
    }
    return true;
}

/*
 * list of folders in doc/text folder
 */
function docTextFoldersList(){
     global $sharedFolder;
     $dir_path = "$sharedFolder/docs/";
     $docFolderList = array(); 
     foreach (scandir("$dir_path/text") as $subDir) {
        $txtDir = "$dir_path/text/$subDir";
        if ($subDir == "." || $subDir == ".." || !is_dir($txtDir)) {
            continue;
        }
        $docFolderList[$subDir]=1;
     }
     return $docFolderList;
}

/*
 * get all facebook folders names
 * need to be analysis from db
 */
function get_all_folderListToAnalysis(){
    $folderList = array();
    $connection = sqlCreateDBConnection("crawlerDB");
    $result = sqlQuery($connection, "SELECT folder_name FROM fb_folder_for_analysis");
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
           array_push($folderList,$row["folder_name"]);
        }
    } else {
        echo "0 results";
    }

//    mysqli_fetch_all($folderList,MYSQLI_ASSOC);
//    mysqli_free_result($folderList);
    return $folderList;
}

/*
 * add facebook folder name 
 * that need to be analysis
 * to db
 */
function add_ToFolderListAnalysis($folderName){
     $connection = sqlCreateDBConnection("crawlerDB");
     $sql = "INSERT INTO fb_folder_for_analysis (folder_name) VALUES ('$folderName')";
     $res =sqlQuery($connection,$sql);
     if ($res) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($connection);
    }
}

/*
 * Delete from db facebook folder name
 * that was successfully analyzed
 */
function delete_FolderListAnalysis($folderName){
    $connection = sqlCreateDBConnection("crawlerDB");
    $sql = "DELETE FROM fb_folder_for_analysis WHERE folder_name='$folderName'";
    $res =sqlQuery($connection,$sql);
    if ($res) {
        echo "Record deleted successfully";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($connection);
    }
}