<?php 


api::upfileajxrequest(function($data){
	$res = [];
	$infos = pathinfo($_FILES["file"]["name"]);
	$ext = strtolower(trim($infos["extension"]));
	if(preg_match("/php|exe|bat/i", $ext)) return;
	if(!preg_match("/jpe?g|png|obj|fbx|mp4/i", $ext)) return;
	if (preg_match("/^\./i", $data["accept"])) {
		if (strtolower(trim($data["accept"])) != strtolower(trim(".$ext")) ) {
			return;
		}
	}
	if ($ext != strtolower(trim($data["ext"])) && !empty($data["ext"])) {
		$extfinal = $data["ext"];
	}else{
		$extfinal = $ext;
	}
	$dist = "public/";
	if (empty($data["dist"])) {
		$dist .= "files";
	}else{
		$dist .= $data["dist"];
	}
	if (empty($data["titre"])) {
		$filename = uniqid().".$extfinal";
		$i = 0;
		while (file_exists($dist."/".$filename)) {
			$i += 1;
			$filename = uniqid()."-$i.$extfinal";
		}
	}else{
		$filename = app::slug($data["titre"]).".$extfinal";
		$i = 0;
		while (file_exists($dist."/".$filename)) {
			$i += 1;
			$filename = app::slug($data["titre"])."-$i.$extfinal";
		}
	}
	$dist .= "/$filename";
	switch (strtolower(trim($_FILES["file"]["type"]))) {
		case 'image/jpeg':
		case 'image/png':
		case 'image/jpg':
		case 'image/gif':
			mkpath(dirname($dist));
			if (($ext != strtolower(trim($data["ext"])) && !empty($data["ext"])) || !empty($data["size"])) {
				mkpath("public/tmpupfile");
				$filename = "public/tmpupfile/".uniqid().".$ext";
				move_uploaded_file($_FILES['file']['tmp_name'], $filename);
				include_once __DIR__."/imagine.phar";
				$imagine = new Imagine\Gd\Imagine();
				$img = $imagine->open($filename);
				if (!empty($data["size"])) {
					$sizedata = explode("-", $data["size"]);
					if (is_numeric($sizedata[0]) && is_numeric($sizedata[1])) {
						$size    = new Imagine\Image\Box($sizedata[0], $sizedata[1]);
						if (strtolower(trim($sizedata[2])) == "inset") {
							$mode = Imagine\Image\ImageInterface::THUMBNAIL_INSET;
						}else{
							$mode = Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND;
						}
						$img = $img->thumbnail($size, $mode);
					}
				}
				$img->save($dist,['jpeg_quality' => 100,'png_compression_level' => 0]);
			}else{
				move_uploaded_file($_FILES['file']['tmp_name'], $dist);
			}
		break;
		case 'application/pdf':
		case 'text/plain':
			mkpath(dirname($dist));
			move_uploaded_file($_FILES['file']['tmp_name'], $dist);
		break;
		default:
			mkpath(dirname($dist));
			move_uploaded_file($_FILES['file']['tmp_name'], $dist);
		break;
	}
	$res["url"] = "/$dist";
	return $res;
});










Route::is("testupload",function(){
	view::use("layout");
?>
	<div class="container" style="margin-top: 88px;" ng-init="list = '/public/files/59a53376db816.jpg'">
		<upfile ng-model="list" max="1"></upfile>
		<pre>{{list | json}}</pre>
	</div>

<?php
});



Route::isJs(function(){
ob_start();
?>
<div style="display: flex;flex-wrap: wrap;">
<style type="text/css">
.boximgupfile img{
    -webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */
    filter: grayscale(100%);
	-webkit-transition: all 200ms ease-in-out;
	-moz-transition: all 200ms ease-in-out;
	-ms-transition: all 200ms ease-in-out;
	-o-transition: all 200ms ease-in-out;
	transition: all 200ms ease-in-out;
}
.boximgupfile:hover img{
    -webkit-filter: grayscale(0); /* Safari 6.0 - 9.0 */
    filter: grayscale(0);
}

.elmupfilediv svg{
	width:30%;
}

</style>

	<div class="elmupfilediv" ng-repeat="elm in list" style="width: {{elm.width}}px;height:{{elm.height}}px;position: relative;margin:{{margin}}px;border:1px solid #ddd;cursor: pointer;overflow: hidden;">
		<div style="position: absolute;top: 5px;right: 5px;z-index: 20;">
			<button class="btn btn-xs glyphicon glyphicon-trash" ng-click="deleteElm($index)"></button>
		</div>
		<div ng-hide="elm.src" style="position: absolute;top: 3px;left: 3px;right: 3px;bottom: 3px;background: #f5f5f5;display: flex;align-items: center;justify-content: center;" >
			<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEYAAABGCAQAAADbJyoPAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAd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SVr755gnhknnGeKFyxSm0dskVpT3KGXEVCdl1uqFnkFgKmV4hfjxHnGe2ffVR3d/wVdeaAvV2yIRQAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxNy0wOC0yOFQxMzoyNTowNiswMjowMOZ3cQ4AAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTctMDgtMjhUMTM6MjU6MDYrMDI6MDCXKsmyAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAABJRU5ErkJggg==">
		</div>
		<div ng-show="elm.src" style="position: absolute;top: 3px;left: 3px;right: 3px;bottom: 3px;background: #fff;">
			<div style="position: absolute;top: 0;left: 0;right: 0;bottom: 0;overflow: hidden;" >
				<img ng-src="{{elm.src}}" style="top: 0;left: {{elm.left}};bottom: 0;width:{{elm.width}}px;height:{{elm.height}}px;position: absolute;">
			</div>
		</div>
		<div style="position: absolute;bottom: 0;left: 0;right: 0;z-index: 2;top: 0;display: flex;justify-content: center;align-items: center;" ng-hide="elm.loading || elm.src || !elm.url">
			<a class="btn btn-default btn-xs" ng-href="{{elm.url}}">Télécharger</a>
		</div>
		<div style="position: absolute;bottom: 0;left: 0;right: 0;z-index: 2;top: 0;display: flex;justify-content: center;align-items: center;background: rgba(0,0,0,0.5);" ng-show="elm.loading">
				<svg viewbox="0 0 100 100">
				  <circle cx="50" cy="50" r="45" fill="#000"/>
				  <path fill="none" stroke-linecap="round" stroke-width="5" stroke="#fff"
				        stroke-dasharray="{{elm.progress*250/100}},250.2"
				        d="M50 10
				           a 40 40 0 0 1 0 80
				           a 40 40 0 0 1 0 -80"/>
				  <text x="50" y="50" text-anchor="middle" dy="7" font-size="20" stroke="#fff">{{elm.progress}}%</text>
				</svg>
		</div>
	</div>


	<div ng-show="list.length<max" ng-click="selectfile()" style="width: {{width?width:150}}px;height:{{height?height:150}}px;position: relative;margin:{{margin}}px;border:1px solid #ddd;cursor: pointer;">
		<div class="boximgupfile" style="position: absolute;top: 3px;left: 3px;right: 3px;bottom: 3px;background: #f5f5f5;display: flex;align-items: center;justify-content: center;" >
			<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEYAAAAuCAYAAACViW+zAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAC4dAAAuHQEHEELWAAAAB3RJTUUH4QgcDDcMq9jUGgAABxJJREFUaN7d23mMXlUZx/HPvB3ASotAp9haglWpVQwhOooaXKMooihYTVArcc2IBq1F3DAuEY3RiEDdRiNqQMUNATFopVpDjRgsagNqKY1irbTDsGil7bRj6x/Pee3t7bnvdt8ZlF8yycy99z3L9z3nOb/znDsDHiANj24oX5qF4/EsPA2Pw7x0fQZ245/YjFvwS6zBeuwqFrR2ZFHt9g38DwBZgJdgCZ6IOR22axJb8Ct8B9fjvn4BmlYwJShH4DUYwRNqtmVXArQC12KiLpxpA1OC8nR8BM9Do4/V7MC3cQE21oEzLWAKUBp4LT4mptBU6XdYjp/3CqcvYDJxI6cZWIYPi4A61dqMc/CDXuD0DKYCxmE4Jv0cnq7dg7/iRfgoZnZQ/CTuxhj+kf4+RATmh+NhHTZzC94s4k5XcAb7BOXxeAVOwaLU8IPSvd2pc7PxkDZF/xk/ESvMrRgXcWNPaussHI0T8WI8I5VbpXm4OAH6TTd97HrElKDMwdniWzmmF8hJY/gyvobbO/zMzARmGV4opmqVVuFMAbqjUdMVmBKUxbgQp9YAAjfh3VhdvpHrQGa0zsbb8F6tp9gHxVSuLLuonqYSHouvimW3jlbhLQqjpF2Dm/cLgLbhE7gTnxH+KKcRXI11nTSsYw9RaMgRYqTUhXJTt1DKgErPf12seLsqPrIAr++0/F7M1YgIfHU0hvN6hVIGVNCoMHhVOh3H0t5idASmUMixItC20g6xwbsQ5+J9uBx/KzzzBfyiLpTM5yfwaeFhcloo3HZbVcaYCqIvxaNblPdrMd9/JnbCTTVwnNgGL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Dzvh7A3lwKsUptTxF7fiWl0Wn+Luptphir/dhdWNkTK4IaKhwbEjnREYYPZB+c5bRoe3VCG8kaRYqg6nl6DmwfFcL9U5FVyqczZ+JSIQyskU9QtnCk8EehUQ2JmLJcSaxltTyx2Nj3M9eIFm6p5N0ukHU7BN8SbSpvse0WjSgPCK0z2lcr+5R8s/+0PiNTCAhFol+KpWr/IcJV0itEEMyFe/xoWr5FWaTj93C123ve16fQMcbh12RSBmStyOfMd+AXNECNjgfBS7bReJOImimCIrPp5qSPtCpqTfjrR6imCQoyIZ8rbjW40LpLitzYvNEpz/1qRwRrrY+Nrp0HbqO40HRdJq2uaF9aOLMouf1fgdQr0HsRaL7KTlxehUPATJTjX4eUiQm/rpIb/M21PMM4Qp60HMNjPaJXg3CZs+xJ8UxyCT/W0mErtFSHie+JY5U0Kp5VlO3FAymHtyKKiR9gtlq/VIhf6fPFPEMeJAD1Tf9/s7jeIncLJrhcmdqVI1e6XUch5rP8AmRMTNpDQQtMAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTctMDgtMjhUMTI6NTU6MTIrMDI6MDAqP5mFAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDE3LTA4LTI4VDEyOjU1OjEyKzAyOjAwW2IhOQAAABJ0RVh0U29mdHdhcmUAZXpnaWYuY29toMOzWAAAACh0RVh0Q29tbWVudABSZXNpemVkIHdpdGggZXpnaWYuY29tIEdJRiBtYWtlco8UFNsAAAAASUVORK5CYII=" alt="" />
		</div>
	</div>
</div>
<?php
$tpl=ob_get_clean();
?>
<script>
	app.directive('upfile', [function () {
		return {
			restrict: 'EA',
			template:<?= json_encode($tpl) ?>,
			scope:{
				ngModel:"=",
				width:"@?",
				height:"@?",
				max:"@?",
				dist:"@?",
				titre:"@?",
				accept:"@?",
				ext:"@?",
				size:"@?",
				obj:"@?",
				changed : "&?"
			},
			link: function ($scope, iElement, iAttrs) {
				

				var boximgupfile = iElement.find(".boximgupfile");
				boximgupfile.on("dragenter",function(e){
				    e.preventDefault();
				    e.stopPropagation();
				    boximgupfile.get(0).style.backgroundColor = "springgreen";
				});
				boximgupfile.on("dragover",function(e){
				    e.preventDefault();
				    e.stopPropagation();
				    boximgupfile.get(0).style.backgroundColor = "springgreen";
				});
				boximgupfile.on("dragleave",function(e){
				    e.preventDefault();
				    e.stopPropagation();
				    boximgupfile.get(0).style.backgroundColor = "#f5f5f5";
				});
				boximgupfile.on('drop', function(e) {
				    e.preventDefault();
				    e.stopPropagation();
				    boximgupfile.get(0).style.backgroundColor = "#f5f5f5";
				    if (e.originalEvent.dataTransfer){
				        if (e.originalEvent.dataTransfer.files.length > 0) {
				            $scope.selectedFiles(e.originalEvent.dataTransfer.files);
				            $scope.$apply();
				        }
				    }
				    return false;
				});



				$scope.width = $scope.width || 150;
				$scope.height = $scope.height || 150;
				$scope.margin = $scope.margin || 5;
				$scope.max = $scope.max || 1;
				$scope.max = $scope.max * 1;
				$scope.stopwatch = false;
				$scope.dist = $scope.dist || "";
				$scope.titre = $scope.titre || "";
				$scope.accept = $scope.accept || "";
				$scope.ext = $scope.ext || "";
				$scope.size = $scope.size || "";
				$scope.obj = !!$scope.obj;
				$scope.deleteElm = function(ndx){
					$scope.list.splice(ndx,1);
					$scope.actModel();
				}
				$scope.createElementFromUrl = function(url){
					var elm = {};
						if ($scope.obj) {
							if (typeof url == "string") {
								elm.url = url;
							}else{
								elm = angular.copy(url);
							}
						}else{
							elm.url = url;
						}
						elm.width = $scope.width || 150;
						elm.height = $scope.height || 150;
						elm.src = $scope.getImageThumb(elm.url);
						elm.left = 0;
						elm.loading = false;
						elm.progress = 0;
						if(elm.src){
							var image = new Image();
							image.onload = function() {
							   elm.width = this.width / (this.height / elm.height);
							   elm.left = (elm.width - $scope.width)/2;
							   $scope.$apply();
							};
							image.src = elm.src;
						}
					return elm;
				}
				$scope.acceptListUrl = function(){
					$scope.list = [];
					if ($scope.ngModel) {
						if ($scope.max>1) {
							for (var i = 0; i < $scope.ngModel.length; i++) {
								$scope.list.push($scope.createElementFromUrl($scope.ngModel[i]));
							}
						}else{
							$scope.list.push($scope.createElementFromUrl($scope.ngModel));
						}
					}
					if (!$scope.list || !($scope.list instanceof Array)) $scope.list = [];
				}
				$scope.actModel = function(){
					$scope.stopwatch = true;
					if ($scope.max*1>1) {
						$scope.ngModel=[];
						$scope.ngModel.splice(0,$scope.ngModel.length);
						for (var i = 0; i < $scope.list.length; i++) {
							if (!$scope.list[i].loading && $scope.list[i].url) {
								if ($scope.obj) {
									var obj = angular.copy($scope.list[i]);
									delete obj.loading;
									delete obj.height;
									delete obj.width;
									delete obj.src;
									delete obj.left;
									delete obj.progress;
									$scope.ngModel.push(obj);
								}else{
									$scope.ngModel.push($scope.list[i].url);
								}
							}
						}

					}else{
						$scope.ngModel = "";
						for (var i = 0; i < $scope.list.length; i++) {
							if (!$scope.list[i].loading && $scope.list[i].url) {
								if ($scope.obj) {
									$scope.ngModel = angular.copy($scope.list[i]);
								}else{
									$scope.ngModel = $scope.list[i].url;
								}
							}
						}

					}
					setTimeout(function(){
						$scope.stopwatch = false;
						$scope.$apply();
					},10);
				}
				$scope.getImageThumb = function(url){
					switch(url.split('.').pop().trim().toLowerCase()){
						case "jpeg":
						case "jpg":
						case "png":
						case "gif":
							return url;
						break;
					}
					return null;
				}

				$scope.selectedFiles = function(files){



						var length = $scope.list.length;
						for (var i = 0; i < Math.min(files.length,$scope.max-length); i++) {
							var elm = {};
							(function(elm,file,index,$scope){
								elm.height = $scope.height || 150;
								elm.width = $scope.width || 150;
								elm.left = 0;
								elm.loading = true;
								elm.progress = 0;
								if (["image/gif", "image/jpeg", "image/png"].indexOf(file.type)>-1) {
									var reader = new FileReader();
									reader.onload = function (e) {
										elm.src = e.target.result;
									    var image = new Image();
									    image.onload = function() {
									       elm.width = this.width / (this.height / elm.height);
									       elm.left = (elm.width - $scope.width)/2;
									       $scope.$apply();
									    };
									    image.src = e.target.result;
										$scope.$apply();
									}
									reader.readAsDataURL(file);
								}else{
									elm.src = null;
								}
							    var formdata = new FormData();
							    formdata.append("file",file);
  								formdata.append("max",$scope.max);
  								formdata.append("dist",$scope.dist);
  								formdata.append("titre",$scope.titre);
  								formdata.append("accept",$scope.accept);
  								formdata.append("ext",$scope.ext);
  								formdata.append("size",$scope.size);
							    var ajax = new XMLHttpRequest();
							    ajax.upload.addEventListener("progress", function(){
							    	elm.progress = Math.ceil((event.loaded / event.total) * 100)-1;
							    	if (elm.progress<0) {
							    		elm.progress = 0;
							    	}
							    	$scope.$apply();
							    }, false);
							    ajax.addEventListener("load", function(res){
							    	elm.progress = 100;
							    	elm.loading = false;
							    	var obj = JSON.parse(res.target.responseText).master;
							    	elm.src = $scope.getImageThumb(obj.url);
							    	elm.url = obj.url;
							    	$scope.actModel();
							    	if($scope.changed){
							    		setTimeout(function(){
							    			$scope.changed({});
							    			$scope.$apply();
							    		},100);
							    	}
							    	$scope.$apply();
							    }, false);
							    ajax.addEventListener("error", function(){
							    	elm.progress = 100;
							    	elm.loading = false;
							    	$scope.$apply();
							    }, false);
							    ajax.addEventListener("abort", function(){
							    	elm.progress = 100;
							    	elm.loading = false;
							    	$scope.$apply();
							    }, false);
							    ajax.open("POST", "?api=upfileajxrequest");
							    ajax.send(formdata);

							})(elm,files[i],i,$scope);
							$scope.list.push(elm);
							$scope.$apply();
						}



				}
				var inputfile = $("<input type='file' "+($scope.max>1?"multiple":"")+" accept='"+$scope.accept+"'>");
				setTimeout(function(){
					inputfile.change(function(e){
						$scope.selectedFiles(this.files);
					});
				},100);
				$scope.selectfile = function(){
					inputfile.click();
				}
				$scope.$watch("ngModel", function(){
					if($scope.stopwatch) return;
					$scope.acceptListUrl();
				});
				$scope.acceptListUrl();
			}
		};
	}])
</script>
<?php
});