import { Component, OnInit } from '@angular/core';
import { ViewerService } from 'src/app/services';

@Component({
  selector: 'app-tileset-editor',
  templateUrl: './tileset-editor.component.html',
  styleUrls: ['./tileset-editor.component.css'],
})
export class TilesetEditorComponent implements OnInit {

  private tilesetEdit;

  constructor(
    private viewerService: ViewerService,
  ) { }

  ngOnInit() {
  }

  editTileset() {
    const currentLayerPrimitive = this.viewerService.getPrimitiveByLayerName(this.viewerService.currentLayerName);
    if (!(currentLayerPrimitive instanceof Cesium.Cesium3DTileset)) {
      alert('当前图层不是模型、倾斜或点云，不能编辑。');
      return;
    }

    const viewer = this.viewerService.viewer;

    if (undefined !== this.tilesetEdit) {
      this.tilesetEdit.destroy();
    }
    this.tilesetEdit = new smart3d.TilesetEdit({
      viewer,
      model: currentLayerPrimitive,
    });
    this.tilesetEdit.start();
    viewer.flyTo(currentLayerPrimitive);
  }

  saveEdit() {
    if (undefined !== this.tilesetEdit) {
      this.tilesetEdit.save();

      // 测试缩放、旋转、平移
      // this.tilesetEdit.scale(2);
      // this.tilesetEdit.rotation(smart3d.EditAxisMode.Z, 45);
      // this.tilesetEdit.translation(smart3d.EditAxisMode.Y, 30);

      // 测试设置 3D tiles 的 modelMatrix
      // this.tilesetEdit.pasteMatrix(Cesium.Matrix4.fromTranslation(new Cesium.Cartesian3(0, 0, 100)));
    }
  }

  resetEdit() {
    if (undefined !== this.tilesetEdit) {
      this.tilesetEdit.reset();
    }
  }

  cancelEdit() {
    if (undefined !== this.tilesetEdit) {
      this.tilesetEdit = this.tilesetEdit.destroy();
    }
  }

  isUrl(value: string): boolean {
    // const reg = /^https?:\/\/(.)*(:)?\/?/;
    const strRegex = '^((https|http|ftp|rtsp|mms)?://)'
      + '?(([0-9a-z_!~*\'().&=+$%-]+: )?[0-9a-z_!~*\'().&=+$%-]+@)?' // ftp 的 user@
      + '(([0-9]{1,3}.){3}[0-9]{1,3}' // IP形式的URL：199.194.52.184
      + '|' // 允许 IP 和域名
      + '([0-9a-z_!~*\'()-]+.)*' // 域名的 www.
      + '([0-9a-z][0-9a-z-]{0,61})?[0-9a-z].' // 二级域名
      + '[a-z]{2,6})' // com
      + '(:[0-9]{1,4})?' // 端口
      + '((/?)|' // 如果没有文件名则不需要反斜杠
      + '(/[0-9a-z_!~*\'().;?:@&=+$,%#-]+)+/?)$';  // 文件路径
    const re = new RegExp(strRegex);
    return re.test(value);
  }

}
