
var hasInspectorError;

function OnLoad() {

	DrawDataReport();
	DrawFtpReport();

	if ($.sessionConst.UseInspecot) {

		CreateTabelInspecorSyncIfNorExsist();
		DrawFtpInspecorReport();
	}

}


function CreateTabelInspecorSyncIfNorExsist(){

	var existorno = new Query("Select type From sqlite_master where name = 'UT_tabelSyncInspecot' And type = 'table'");
	var exorno = existorno.ExecuteCount();
	if (exorno == 0) {
		DB.CreateTable("tabelSyncInspecot", ["Date","status","Message"]);
	}
}
// -------------------- Sync Data ------------
function SyncData() {

	if ( $.sessionConst.autoSyncIsActive ) {
		 Dialog.Message("Проходит автосинхронизация. Ждите.");}
else {
		$.dataSyncReport.Visible = false;
		$.dataSyncError.Visible = false;
		$.dataSyncLayout.Visible = true;
		$.dataSyncIndicator.Start();

		DB.Sync(SyncDataFinish);
	}

}

function SyncDataFinish() {
	$.dataSyncIndicator.Stop();
	$.dataSyncLayout.Visible = false;

	DrawDataReport();

	$.Remove("sessionConst");
	Global.SetSessionConstants();
	Global.SetGps();
	Indicators.SetIndicators();
	Workflow.Refresh([]);
}

function DrawDataReport() {
	var at = Translate["#at#"];
	var date = DB.LastSyncTime.ToString("dd.MM.yy ");
	var time = DB.LastSyncTime.ToString(" HH:mm");

	if (DB.SuccessSync) {
		$.dataSyncReport.Text = date + at + time;
		$.dataSyncReport.Visible = true;
		$.dataSyncError.Visible = false;
	} else {
	//	Dialog.Message("Нет доступа к серверу. Проверьте Ваше интернет соединение.");
		$.dataSyncError.Text = Translate["#error#"] + ": " + date + at + time;
		$.dataSyncError.Visible = true;
		$.dataSyncReport.Visible = false;
	}
}

// -------------------- Sync Ftp ------------

function SyncFtp() {
	$.ftpSyncReport.Visible = false;
	$.ftpSyncError.Visible = false;
	$.ftpSyncLayout.Visible = true;
	$.ftpSyncIndicator.Start();

	FileSystem.UploadPrivate(UploadPrivateCallback);
}

function UploadPrivateCallback(args) {
	if ($.sessionConst.UseInspecot)
		SyncInspectorFiles();
	if (args.Result) {
		// Remove private files
			if (!$.sessionConst.UseInspecot || hasInspectorError == "AllFine")
			{
				FileSystem.ClearPrivate();
			}


		FileSystem.SyncShared(SyncSharedCallback);
	} else {
		FileSystem.HandleLastError();
		SyncFtpFinish();
	}

}

function SyncSharedCallback(args) {
	if (!args.Result) {
		FileSystem.HandleLastError();
	}

	SyncFtpFinish();
}

function SyncFtpFinish() {



	$.ftpSyncIndicator.Stop();
	$.ftpSyncLayout.Visible = false;

	DrawFtpReport();

}

function SyncInspectorFiles(){

	$.ftpSyncInspectorReport.Visible = false;
	$.ftpSyncInspectorError.Visible = false;
	$.ftpSyncInspectorLayout.Visible = true;
	$.ftpSyncInspecorIndicator.Start();

	hasInspectorError="";
	var q  = new Query("Select Id As id, FullFileName As FFN From Document_Visit_Files Where InspecroId = -1");
	var res = q.Execute();
	var countFile = q.ExecuteCount();
	while(res.Next()){
		SyncInspecorFile(Variables.GetContext().LocalStorage+res.FFN,res.id,res.FFN);
	}

	var status;
	if (hasInspectorError != "")
	{
		status = 0;
		Dialog.Message(Translate["#"+hasInspectorError+"#"]);
	}
	else
	{
		status = 1;
		hasInspectorError = "AllFine";
	}
	$.ftpSyncInspecorIndicator.Stop();
	$.ftpSyncInspectorLayout.Visible = false;


	if (countFile>0)
	{
	var q2 = new Query("Insert into UT_tabelSyncInspecot values(datetime('now','localtime'),'"+status+"','"+hasInspectorError+"')");
				q2.Execute().Close();
	}
	DrawFtpInspecorReport();

}

function GetImagePath(visitID, pictID) {
	var pathFromVisit = Images.FindImage(visitID, pictID, null, "Document_Visit_Files");
	return (pathFromVisit);
}

function cleanString(input) {
    var output = "";
    for (var i=0; i<input.length; i++) {
        if (input.charCodeAt(i) <= 127) {
            output += input.charAt(i);
        }
    }
    return output;
}

function CheckUrl(uri){
	return Dns.IsValidHostAddress(uri);
}

function SyncInspecorFile(path,id,localpath){

	if (FileSystem.Exists(localpath))
	{

		var url = TrimAll($.sessionConst.InspectorUrl);

		if (Right(url, 1) != "/")
			url = url + "/";
		else
			url = url + "";

		if (!CheckUrl(cleanString(url)) || TrimAll($.sessionConst.TokenInspector)=="")
		{
			hasInspectorError = "ErrorSetting";
			return;
		}

		url = url + "api/v1.4/uploads/";

		var client = new RestClient(cleanString(url)); // for test https://1cbit.inspector-cloud.ru/api/v1.4/uploads/
		var request = new RestRequest(Method.POST);

		request.AddHeader("cache-control", "no-cache");
		request.AddHeader("authorization", "Token " + TrimAll($.sessionConst.TokenInspector)); // for test Token ba25f87421399baedad4c9738db8db74661a6fd2

		request.AddFile("datafile",path,"image/jpeg");

		var response = client.Execute(request);

		if (response.StatusCode == HttpStatusCode.Created)
		{
			 var jsonObj = JsonConverter.Deserialize(response.Content);

			if (jsonObj != null)
			{
				 if (jsonObj.hasOwnProperty("id")) {
				 	var obj = id.GetObject();
				 	obj.InspecroId = jsonObj.id;
				 	obj.Save();
				 	var deleteTranStatus = new Query("Delete From ___TranStatus ");
				 	deleteTranStatus.Execute().Close();
				 }
				 else
				 {
				 	hasInspectorError = "InspectorError";
				 }
			}
			else
			{
				hasInspectorError = "InspectorError";
			}
		}
		else
		{
			hasInspectorError = response.StatusCode;
			//Dialog.Message(response.StatusCode);
		}
	}else{
		//hasInspectorError="FileNotExsist";
	}
}

function DrawFtpReport() {

	var at = Translate["#at#"];
	var date = FileSystem.LastSyncTime.ToString("dd.MM.yy ");
	var time = FileSystem.LastSyncTime.ToString(" HH:mm");

	if (FileSystem.SuccessSync) {

		$.ftpSyncReport.Text = date + at + time;
		$.ftpSyncReport.Visible = true;
		$.ftpSyncError.Visible = false;

	} else {

		if (isDefault(FileSystem.LastSyncTime))
			$.ftpSyncError.Text = Translate["#Synchronization_has_not_been_performed#"];
		else
			$.ftpSyncError.Text = Translate["#error#"] + ": " + date + at + time;
		$.ftpSyncError.Visible = true;
		$.ftpSyncReport.Visible = false;

	}
}
function DrawFtpInspecorReport() {

	var at = Translate["#at#"];
	var q = new Query("Select Date As dt,status As s From UT_tabelSyncInspecot Order By Date DESC Limit 1");
	var unitTime = q.Execute();
	if (unitTime.dt!=null) {
			var date = DateTime.Parse(unitTime.dt).ToString("dd.MM.yy ");
			var time = DateTime.Parse(unitTime.dt).ToString(" HH:mm");
	}

	if (unitTime.s == 1) {

		$.ftpSyncInspectorReport.Text = date + at  + time;
		$.ftpSyncInspectorReport.Visible = true;
		$.ftpSyncInspectorError.Visible = false;

	} else {

		if (unitTime.dt==null)
			$.ftpSyncInspectorError.Text = Translate["#Synchronization_has_not_been_performed#"];
		else
			$.ftpSyncInspectorError.Text = Translate["#error#"] + ": " + date + at + time;

		$.ftpSyncInspectorError.Visible = true;

		$.ftpSyncInspectorReport.Visible = false;
	}
}
function ClearPrivateFtp()
{
	FileSystem.ClearPrivate();
}
