import { Component, OnInit, ViewChild, AfterViewInit, ElementRef, Input, Output, EventEmitter, ViewContainerRef, SimpleChanges, OnChanges, OnDestroy, AfterViewChecked } from '@angular/core';
import { EmployeeSandboxComponent } from 'app/employee/employee-dashboard/employee-sandbox/employee-sandbox.component';
import { AuthService } from 'app/services/auth.service';
import * as sb from 'app/models/sandbox-progress.model';
import { ProgressStateSetupWorkspaceService } from 'app/employee/employee-dashboard/employee-sandbox/progress-state-setup-workspace.service';
import { ToastsManager } from 'ng2-toastr';
import { environment } from '../../../environments/environment.dev';
@Component({
  selector: 'app-employee-sandbox-progress-icon',
  templateUrl: './employee-sandbox-progress-icon.component.html',
  styleUrls: ['./employee-sandbox-progress-icon.component.scss']
})

export class EmployeeSandboxProgressIconComponent implements OnInit, AfterViewInit, OnChanges, OnDestroy {
  set_interval: any;
  draw: (current: any) => void;
  @Input() dataState: sb.SandboxSetupProcessWorkSpace = { state: sb.state.NONE };
  public counter = 1;
  public launchOpen = false;
  @ViewChild('progressBar') pb: ElementRef;
  imageUrl: string = environment.imageUrl;
  context: CanvasRenderingContext2D;

  constructor(private el: ElementRef, private auth: AuthService, private toastr: ToastsManager, private pSService: ProgressStateSetupWorkspaceService) {

  }

  ngOnChanges(changes: SimpleChanges): void {
    if (this.dataState.state === sb.state.Error) {
      this.toastr.error('Something went wrong in the Setup Workspace...');
      this.dataState.show = false;
      this.ngOnDestroy();
    }
  }

  ngOnInit() { }

  private drawProgressBar() {
    const timeFromCreated = (Date.now() - this.dataState.data.createdTime) / (1000 * 60);
    if (timeFromCreated < 30) {
      this.counter = timeFromCreated * 100 / 30;
      setTimeout(() => {

        for (let index = 0; index < this.counter; index++) {
          requestAnimationFrame(() => {
            if (this.draw) {
              this.draw(index / 100);
              this.pSService.ProgressIconComponent.next({ state: sb.state.InProgress, counter: index });
            }
          });
        }
      }, 0);

      // this.counter = 0;
      this.pSService.ProgressIconComponent.next({ state: sb.state.InProgress, counter: this.counter });
      this.set_interval = setInterval(() => {

        requestAnimationFrame(() => {
          if (this.draw) {
            this.draw(this.counter / 100);
            this.pSService.ProgressIconComponent.next({ state: sb.state.InProgress, counter: this.counter });
            if (this.dataState.state === sb.state.Error) { this.counter += 10; }
          }
        });

        if (this.counter >= 100) {
          clearInterval(this.set_interval);
          if (this.dataState.state === sb.state.Completed) {
            this.pSService.ProgressIconComponent.next({ state: sb.state.Completed, counter: this.counter });
          }
        }
        this.counter += 1;
      }, 18000);

    } else {
      this.counter = 100;
      this.dataState.state = timeFromCreated < 30 ? sb.state.InProgress : sb.state.Completed;
      setTimeout(() => {
        if (this.counter = 100) {

          for (let i = 0; i < this.counter; i++) {

            requestAnimationFrame(() => {
              if (this.draw) {
                this.draw(i / 100);
              }
            });
            this.pSService.ProgressIconComponent.next({ state: sb.state.Completed, counter: i });
          }
        }
      }, 0);
    }


  }

  ngAfterViewInit() {
    this.context = this.pb.nativeElement.getContext('2d');
    const ctx = this.context;

    const circ = Math.PI * 2;
    const quart = Math.PI / 2;

    ctx.clearRect(0, 0, 100, 100);
    const sandboxIcon = new Image();
    sandboxIcon.width = 84;
    sandboxIcon.src = 'assets/img/sandbox/Sandbox_Icon@2x.png';
    sandboxIcon.onload = (ev) => {
    //  ctx.globalCompositeOperation = 'source-over';
     ctx.drawImage(sandboxIcon, 3, 3, 94, 94);
     this.drawProgressBar();
    };


    ctx.beginPath();
    ctx.strokeStyle = 'white';
    ctx.lineCap = 'square';
    ctx.lineWidth = 4.0;
    ctx.arc(50, 50, 48, - quart, ((circ) * 1) - quart, false);
    ctx.stroke();


    ctx.beginPath();
    ctx.strokeStyle = '#00CCFF';
    ctx.lineCap = 'square';
    ctx.closePath();
    ctx.fill();
    ctx.lineWidth = 3.0;

    this.draw = (current) => {
      ctx.beginPath();
      ctx.arc(50, 50, 44, -(quart), ((circ) * current) - quart, false);
      ctx.stroke();
      ctx.closePath();

    };
    this.dragElement();

  }

  private dragElement() {
    let offset: number[];

    const dragMouseDown = (e) => {
      e.stopPropagation();
      e = e || window.event;

      // get the mouse cursor position at startup:

      offset = [
        this.el.nativeElement.offsetLeft - e.clientX,
        this.el.nativeElement.offsetTop - e.clientY
      ];

      // call a function whenever the cursor moves:
      document.body.onmousemove = elementDrag;
    };

    const elementDrag = (e) => {
      e.stopPropagation();
      e = e || window.event;
      // calculate the new cursor position:
      const mousePosition = {

        x: e.clientX,
        y: e.clientY

      };

      this.el.nativeElement.style.left = (mousePosition.x + offset[0]) + 'px';
      this.el.nativeElement.style.top = (mousePosition.y + offset[1]) + 'px';

    };

    const closeDragElement = () => {

      /* stop moving when mouse button is released:*/
      document.body.onmousemove = null;
    };

    this.el.nativeElement.onmouseup = closeDragElement;
    this.el.nativeElement.onmousedown = dragMouseDown;
  }

  abortSandbox() {

    this.auth.terminateAwsWorkspaceStatus({Id:this.dataState.data.workSpaceId,sname:this.dataState.data.adId}).then(resp => {

      console.log(resp,'terminate workspace')

      this.auth.updateAwsWorkspaceStatus(this.dataState.data.adId, 'Terminated')
        .subscribe(res => {
            this.dataState.show = false;
            this.pSService.ProgressIconComponent.next({ state: sb.state.NONE, counter: 0 });
            this.pSService.setupProcessWorked.next({ show: false, state: sb.state.NONE, data: { createdTime: Date.now() }});
            this.toastr.success('Workspace terminated successfully');
          }, (e) => {
            this.toastr.error('The Abort was wrong');
          }
        );

    }).catch(err => {
            console.log(err,'error')
            this.toastr.error('The Abort was wrong');
    })



  }
  ngOnDestroy(): void {
    clearInterval(this.set_interval);
    this.pSService.ProgressIconComponent.next({ state: sb.state.NONE, counter: 0 });
  }
}
