<?php

require_once 'demosettings.php';
require_once 'slotToCaption.php';
require_once 'write_log.php';
	/*require_once("demosettings.php");
	$mysqli = new mysqli($databaseHost, $databaseUser, $databasePass, $databaseName);
	$res = $mysqli->query("select * from sentiment");
	$sentimentArr = array();
	$sentimentArr['All'] = "All";
	$sentimentArrPos = array();
	$sentimentArrNeg = array();	
	while ($r = $res->fetch_object()){
		$key = $r->sentiment;
		$sentimentArr[$key] = $key;
		$key = $r->sentiment . "-negative"; 
		$sentimentArrNeg[$key] = $key;
		$key = $r->sentiment . "-positive"; 
		$sentimentArrPos[$key] = $key;		 		
	}*/

/*
 * 
 */
function get_pro_anti_concepts($type) {
    $mysqli = sqlCreateConnection("get_pro_anti_concepts");
    
    $sentimentFields = getSentimentFields($mysqli);
    foreach ($sentimentFields[$type] as $v) {
         $sentimentConceptsArr[] = $v;
    }
    sqlClose($mysqli, "get_pro_anti_concepts");
      return $sentimentConceptsArr;
}

function getSentimentFields($mysqli){
    require_once 'parseUtils.php';
//    $anti = getSubFields($mysqli,null,  "anti_concept","");	
//    $pro = getSubFields($mysqli, null, "pro_concept","");
    $anti = getSubFields($mysqli, "anti_concept","");	
    $pro = getSubFields($mysqli, "pro_concept","");
	$arr = array("anti" => $anti, "pro" => $pro);
	foreach ($arr as $s => $v){
		foreach ($v as $n){
            write_to_log("TRACE", " Sentiment key - $n doesn't exsist on sentimentConceptToGroup Array"); 
    		$res[$s][$n] = $n;
			
		}	
	}
	ksort($res["pro"]);
	ksort($res["anti"]);
	
	return array("searchSentiment"=>array(						
						"Positive"=>"Positive",
						"Negative"=>"Negative"),
				"entities"=>array(
						"Places"=>"place_object",
						"Person"=>"person_object",
						"Organisation"=>"organizational_identity",
				        "Event"=>"event",
				    "Idea"=>"abstract_idea_entity"
				),
				"anti"=>$res["anti"],
				"pro"=>$res["pro"]);
}


function getSentimentParams($searchSentiment){
        $searchSentiment_arr = $searchSentiment;
        if(!is_array($searchSentiment)){
            $searchSentiment_arr = [$searchSentiment];
        }
        foreach($searchSentiment_arr as $searchSentimentElement){
            $e = explode("^", $searchSentimentElement);
            $sentiment = $e[0];
            $type = $e[1];
            if (!preg_match("/^[a-z_]+$/", $type)) {
                write_to_log("ERROR", "incorrect talbe type: $type");
                die("Error!");
            }
            $sentiment_string = $e[2];
            $sentimentInstances = (count($e) < 4) ? NULL : ((empty($e[3])) ? NULL : explode(",", $e[3]));
            $sentimentConcepts = (count($e) < 5) ? NULL : explode(",", $e[4]);
            $res[] = array('sentiment'=>$sentiment,'type'=>$type,'sentiment_string'=>$sentiment_string,'sentimentInstances'=>$sentimentInstances,'sentimentConcepts'=>$sentimentConcepts );
        }
        return $res;
}   
 
function sentiment($searchSentiment, $mysqli, $returnEmpty, $arr_id, $searchString, $isAdmin, $username) {
    global $oneSearchQuery;

    if ($searchSentiment != "" && !$returnEmpty) {
        write_to_log("PERMORMENCE", "search start sentiment time -" . date('H:i:s' . substr((string) microtime(), 1, 8)));
        $personId = array();
        $sql = "";
        $params = getSentimentParams($searchSentiment);
        $sentiment = $params['sentiment'];
        $type=  $params['type'];
        $sentiment_string = $params['sentiment_string'];
        $sentimentInstances = $params['sentimentInstances'];
        $sentimentConcepts = $params['sentimentConcepts'];
        $sentimentConceptsArr = getSentimentConceptsArr($sentimentConcepts);
        $externalCondition = ["sentimentType" => $sentiment, "instances" => $sentimentInstances, "concepts" => $sentimentConceptsArr];
        $type2entType = ["person_object" => "person,email", "place_object" => "place", "organizational_identity" => "organization"];
        
        if (array_key_exists($type, $type2entType) && !empty($sentiment_string)) {
            $entitiesToSearch[] = array("text" => $sentiment_string, "condition" => $externalCondition, "type" => $type2entType[$type]);
            $sentimentInSearchEntities = true;
            write_to_log("TRACE", "sentiemnt entities:" . print_r($entitiesToSearch, true));

            $sql = "";
        } else {
            $sqls = [];
            foreach (parseAndReplaceExternalConditions($mysqli, $externalCondition, $type, $type) as $condObj) {
                $tmpSql = "SELECT DISTINCT $type.docId FROM $type {$condObj->table}, files WHERE {$condObj->wherePhrase} files.id = $type.docId ";
                if (!empty($sentiment_string)) {
                    $sentiment_string = $mysqli->real_escape_string($sentiment_string);
                    $tmpSql .= " AND ($type.name LIKE('%$sentiment_string%') or $type.orgText LIKE('%$sentiment_string%')) ";
                }
                if (!$isAdmin) {
                    $tmpSql .= " AND files.username='$username'";
                }
                $sqls[] = $tmpSql;
            }
            $sql = join(" UNION ", $sqls);
            if (empty($sql)) {
                write_to_log("ERROR", "No SQL was generated for sentiment: $searchSentiment");
                $returnEmpty = true;
            }
        }
        if (strlen($sql) > 1) {
            if ($oneSearchQuery) {
                $searchSqls[] = array("docId" => "docId", "Query" => $sql);
            } else {
                $res = sqlQuery($mysqli, $sql);
                if (empty($arr_id)) {
                    if (!empty($res)) {
                        while ($row = $res->fetch_object()) {
                            if (!empty($row->docId)) {
                                $arr_id[$row->docId] = $row->docId;
                            }
                        }
                    }
                } else {
                    $arr = array();
                    if (!empty($res)) {
                        while ($row = $res->fetch_object()) {
                            if (!empty($row->docId)) {
                                if (key_exists($row->docId, $arr_id)) {
                                    $arr[$row->docId] = $row->docId;
                                }
                            }
                        }
                    }
                    $arr_id = $arr;
                }
            }
        } elseif (!empty($personId)) {
            if (empty($arr_id)) {
                $arr_id = $personId;
            } else {
                $arr = array();
                foreach ($personId as $p) {
                    if (key_exists($p, $arr_id)) {
                        $arr[$p] = $p;
                    }
                }
                $arr_id = $arr;
            }
        }
        //if not results - treat as empty result (unless sentiment should be searched in searchEntities
        if (empty($arr_id) && !$sentimentInSearchEntities && !$oneSearchQuery) {
            $returnEmpty = true;
        }
        if (strlen($searchString) > 0) {
            $searchString .= ",";
        }
        $searchString .= " Sentiment-" . $searchSentiment;
        write_to_log("PERMORMENCE", "search end sentiment time -" . date('H:i:s' . substr((string) microtime(), 1, 8)));
    }

    return array('searchSentiment' => $searchSentiment, 'returnEmpty' => $returnEmpty, 'arr_id' => $arr_id, 'searchString' => $searchString);
}

 
function getSearchStringSentiment_obs($mysqli, $username, $searchSentiment){
    $params = getSentimentParams($searchSentiment);
    $sentiment_string = $params['sentiment_string'];
    $table = $params['type'];
    $sent = $params['sentiment']=="Positive" ? "pro" : "anti";
    $sql = "SELECT docid FROM $table WHERE $sent <> '' ";
    $sentiment_string = $mysqli->real_escape_string($sentiment_string);
    $sql .= " AND ($table.name LIKE('%$sentiment_string%') or $table.orgText LIKE('%$sentiment_string%')) ";
    if (!getUserPermission(CAN_SHOW_ALL_USER))
        $Sql .= " AND $table.username='$username' ";
    $sql .= "GROUP BY docid";
    return $sql;

}
 function getSearchStringSentiment($searchSentiment, $isAdmin, $username,$mysqli) {
     $entitiesToSearch = array();
     $table2CaptionsArray = array();
    //$searchSentiment = $searchValue;
    write_to_log("PERMORMENCE", "search start sentiment time -" . date('H:i:s' . substr((string) microtime(), 1, 8)));
    //$personId = array();
    $sqls = [];
    $params_arr = getSentimentParams($searchSentiment);
    
    foreach($params_arr as $params){
        $sentiment = $params['sentiment'];
        $type=  $params['type'];
        $sentiment_arr = explode("&", $params['sentiment_string']);
        $sentimentInstances = $params['sentimentInstances'];
        $sentimentConcepts = $params['sentimentConcepts'];
        if(empty($sentimentConcepts) || in_array('All', $sentimentConcepts)){
            if($sentiment=="Positive"){
                $sentimentConcepts = get_pro_anti_concepts('pro');
            }
            elseif($sentiment == "Negative"){
                $sentimentConcepts = get_pro_anti_concepts('anti');
            }
            else{
                write_to_log("ERROR", "Invalid Sentiment was sent to sentiment search");
                return null;            
            }
        }
       $sentiment = ($sentiment == 'Negative') ? 'anti' : 'pro';
        
        $sentTable = $sentiment . '_concept';
        foreach ($sentimentConcepts as $v) {
            if(empty($v)){
                continue;
            }
            $escaped[] = $mysqli->real_escape_string($v);
        }
        $sub_concepts_sql = !empty($escaped) ? "$sentTable.value IN('" . join("', '", $escaped) . "')" : " TRUE ";
        $sentimentConceptsArr = getSentimentConceptsArr($sentimentConcepts);
    
        foreach ($sentiment_arr as &$entity){
            $entity = $mysqli->real_escape_string($entity);
        }
        $entities_str = implode("','", $sentiment_arr);
        $sqls[] = "SELECT $type.docId FROM $type  JOIN $sentTable ON $type.docId = $sentTable.docId AND $type.id = $sentTable.instanceId AND $sentTable.instanceType =
        '$type'  WHERE $sub_concepts_sql AND  $type.name IN ('$entities_str')";
    }
    $sql_res = implode(" UNION ", $sqls);
    return $sql_res;
    
    //special case - abstract_idea_entity
//     if ($type == 'abstract_idea_entity') {
//         $escaped = [];
//         $sql_str_id = sql_getSentimentsDocsIds($isAdmin, $username, $type, null, $sentiment_string, 'date', null); //will get all the docs Ids
//         $sentiment = ($sentiment == 'Negative') ? 'anti' : 'pro';
//         $sentTable = $sentiment . '_concept';
//         foreach ($sentimentConcepts as $v) {
//             $escaped[] = $mysqli->real_escape_string($v);
//         }
//         $sub_concepts_sql = !empty($escaped) ? "$sentTable.value IN('" . join("', '", $escaped) . "')" : " TRUE ";

//         return abstract_idea_sent($sentiment, $type, null, $sql_str_id, $sub_concepts_sql); //will get me the pro/anti of those docs
//     }



    
//     $externalCondition = ["sentimentType" => $sentiment, "instances" => $sentimentInstances, "concepts" => $sentimentConceptsArr];
//     $type2entType = ["person_object" => "person,email", "place_object" => "place", "organizational_identity" => "organization"];
    
//     if (array_key_exists($type, $type2entType) && !empty($sentiment_string)) {
//         $entitiesToSearch[] = array("text" => $sentiment_string, "condition" => $externalCondition, "type" => $type2entType[$type]);
//         $sentimentInSearchEntities = true;
//         write_to_log("TRACE", "sentiemnt entities:" . print_r($entitiesToSearch, true));
//         $table2CaptionsArray = entities2CaptionLists($mysqli, $entitiesToSearch);
//         $sql = $entitiesToSearch[0]["Query"];
//     } else {
//         $sqls = [];
//         foreach (parseAndReplaceExternalConditions($mysqli, $externalCondition, $type, $type) as $condObj) {
//             $tmpSql = "SELECT DISTINCT $type.docId FROM $type {$condObj->table}, files WHERE {$condObj->wherePhrase} files.id = $type.docId ";
//             if (!empty($sentiment_string)) {
//                 $sentiment_string = $mysqli->real_escape_string($sentiment_string);
//                 $tmpSql .= " AND ($type.name LIKE('%$sentiment_string%') or $type.orgText LIKE('%$sentiment_string%')) ";
//             }
//             if (!getUserPermission(CAN_SHOW_ALL_USER))
//                 $tmpSql .= " AND files.username='$username'";
//                 $sqls[] = $tmpSql;
//         }
//         $sql = join($unionPhrase, $sqls);
//         if (empty($sql)) {
//             write_to_log("ERROR", "No SQL was generated for sentiment: $searchSentiment");
//             $returnEmpty = true;
//         }

}



function getSentimentConceptsArr($sentimentConcepts) {
    if (sizeof($sentimentConcepts) > 0) {
        //replace key to value
        foreach ($sentimentConcepts as $v) {
          
                $sentimentConceptsArr[] = $v;
            
        }
        return $sentimentConceptsArr;
    }
}

?>