import { Component, Inject, OnInit } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Observable } from 'rxjs';
import { FetcherService } from '../fetcher.service';
import { GET_JIRA_TICKETS_API, CREATE_JIRA_TICKET_API, UPDATE_JIRA_TICKET_API } from '../urls';
import { getJiraTicketsResponse, createJiraTicketResponse, updateJiraTicketResponse } from '../responses';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';

export interface TicketData {
  tid: string;
  pname:string;
  tname: string;
  tcontent: string;
}

export interface ListData{
  tid: string;
  name : string;
  content: string;
}

/**
 * This component list the JIRA tickets in four columns as TO DO, IN PROGRESS, DONE, and BACKLOG.
 */
@Component({
  selector: 'app-jira',
  templateUrl: './jira.component.html',
  styleUrls: ['./jira.component.css']
})
export class JiraComponent implements OnInit {
  id: number;
  name: string;
  temp_tname = '';
  temp_tcontent = '';
  temp_tid = '';
  pid = "";
  col_name = GRID_NAME;
  to_do = new Array<ListData>();
  in_prog = new Array<ListData>();
  done = new Array<ListData>();
  backlog = new Array<ListData>();

  /**
   * Creating observable component to get, update and create tickets.
   */
  getJira_stat$ = new Observable<getJiraTicketsResponse>();
  updateJira_stat$ = new Observable<updateJiraTicketResponse>();
  createJira_stat$ = new Observable<createJiraTicketResponse>();
  constructor(public dialog:MatDialog, private fetcherService: FetcherService, private http: HttpClient, private router: Router, private cookieService: CookieService) {
    console.log(window.history.state);
    this.id = window.history.state.id;
    this.name = window.history.state.name;
  }
  calColCount(){
    console.log(window.innerWidth);
    if(window.innerWidth > 1000){
      return 4;
    }else if(window.innerWidth > 600){
      return 2;
    }else{
      return 1;
    }
  }

  /**
   * Open dialog box to create JIRA tickets. and Post the same to DB. 
   */
  openDialog(){
    const dialogRef = this.dialog.open(CreateTicketDialog, {
      data: {tid: this.temp_tid, pname:this.name, tname: this.temp_tname, tcontent: this.temp_tcontent,
      },
    });

    dialogRef.afterClosed().subscribe(result => {
      this.createJira_stat$ = this.http.post<createJiraTicketResponse>(CREATE_JIRA_TICKET_API, {
        pid: this.pid.replace("'",''),
        name: result.tname,
        content: result.tcontent,
        status: 'to_do',
      });
      this.createJira_stat$.subscribe(
        (response) => {
          console.log(response);
          if(response.status == true){
            this.to_do.push({tid: response.tid, name: result.tname, content: result.tcontent});
          }
          else{
            console.log('fail');
          }
        });
    });
  }

  calRowHeight(){
    let max_issue = Math.max(this.to_do.length,this.in_prog.length,this.done.length,this.backlog.length)
    let str = '';
    str = '1:'+(max_issue/3);
    return str;
  }

  /**
   * Returns list to HTML page
   */
  fetchList(id: number) {
    if(id == 1){
      return this.to_do;
    }
    else if(id == 2){
      return this.in_prog;
    }
    else if(id == 3){
      return this.done;
    }
    else{
      return this.backlog;
    } 

  }

  /**
   * Update the status Jira Ticket and Post the same to Backend Server.
   * This is called from the move to button, and their respective function calls in the next the three functions.
   */
  updateStatus(tid:string, updated_status: string){
    this.updateJira_stat$ = this.http.post<updateJiraTicketResponse>(UPDATE_JIRA_TICKET_API, {
      tid: tid,
      status: updated_status,
    });
    this.updateJira_stat$.subscribe(
      (response) => {
        if(response.status == true){
        }
        else{
        }
      }
    );
  }

  moveToInProgress(tid: string, list_name: string ){
    this.updateStatus(tid, 'in_progress');
    if (list_name == 'to_do') {
      for (let i = 0; i< this.to_do.length; i++){
        if( this.to_do[i].tid == tid){
          this.in_prog.push(this.to_do[i]);
          this.to_do.splice(i,1);
          break;
        }
      }
    } else if (list_name == 'done') {
      for (let i = 0; i< this.done.length; i++){
        if( this.done[i].tid == tid){
          this.in_prog.push(this.done[i]);
          this.done.splice(i,1);
          break;
        }
      }
    } else if (list_name == 'backlog') {
      for (let i = 0; i< this.backlog.length; i++){
        if( this.backlog[i].tid == tid){
          this.in_prog.push(this.backlog[i]);
          this.backlog.splice(i,1);
          break;
        }
      }
    }
  }
  
  moveToDone(tid: string, list_name: string ){
    this.updateStatus(tid, 'done');
    if (list_name == 'to_do') {
      for (let i = 0; i< this.to_do.length; i++){
        if( this.to_do[i].tid == tid){
          this.done.push(this.to_do[i]);
          this.to_do.splice(i,1);
          break;
        }
      }
    } else if (list_name == 'in_prog') {
      for (let i = 0; i< this.in_prog.length; i++){
        if( this.in_prog[i].tid == tid){
          this.done.push(this.in_prog[i]);
          this.in_prog.splice(i,1);
          break;
        }
      }
    } else if (list_name == 'backlog') {
      for (let i = 0; i< this.backlog.length; i++){
        if( this.backlog[i].tid == tid){
          this.done.push(this.backlog[i]);
          this.backlog.splice(i,1);
          break;
        }
      }
    }
  }

  moveToToDo(tid: string, list_name: string ){
    this.updateStatus(tid, 'to_do');
    if (list_name == 'in_prog') {
      for (let i = 0; i< this.in_prog.length; i++){
        if( this.in_prog[i].tid == tid){
          this.to_do.push(this.in_prog[i]);
          this.in_prog.splice(i,1);
          break;
        }
      }
    } else if (list_name == 'done') {
      for (let i = 0; i< this.done.length; i++){
        if( this.done[i].tid == tid){
          this.to_do.push(this.done[i]);
          this.done.splice(i,1);
          break;
        }
      }
    } else if (list_name == 'backlog') {
      for (let i = 0; i< this.backlog.length; i++){
        if( this.backlog[i].tid == tid){
          this.to_do.push(this.backlog[i]);
          this.backlog.splice(i,1);
          break;
        }
      }
    }
  }

  /**
   * On initialization, fetch JIRA tickets for the respective project from DB and divide them into TO DO, IN PROGRESS, DONE and BACKLOG.
   */
  ngOnInit(): void {
    this.fetcherService.setCurrentProjectId(this.id);
    this.pid = this.cookieService.get('pid');
    this.getJira_stat$ = this.http.get<getJiraTicketsResponse>(GET_JIRA_TICKETS_API+'?pid='+this.pid)
    this.to_do.length = 0;
    this.in_prog.length = 0;
    this.done.length = 0;
    this.backlog.length = 0;

    this.getJira_stat$.subscribe(
      (data) => {
        for(let i =0; i<data.files.length; i++){
          if(data.files[i].status == 'to_do'){
            this.to_do.push({tid: data.files[i].tid, name: data.files[i].name, content: data.files[i].content});
          }
          else if(data.files[i].status == 'in_prog'){
            this.in_prog.push({tid: data.files[i].tid, name: data.files[i].name, content: data.files[i].content});
          }
          else if(data.files[i].status == 'done'){
            this.done.push({tid: data.files[i].tid, name: data.files[i].name, content: data.files[i].content});
          }
          else{
            this.backlog.push({tid: data.files[i].tid, name: data.files[i].name, content: data.files[i].content});
          }
        }
      }
    );
  }

}

/**
 * This component handles the dialog box for Create Ticket. It injects the data items to be modified.
 * It modifies the TicketData and return the same.
 */
@Component({
  selector: 'create-ticket-dialog',
  templateUrl: './create-ticket-dialog.html',
  styleUrls: ['./jira.component.css']
})
export class CreateTicketDialog {
  constructor(
    public dialogRef: MatDialogRef<CreateTicketDialog>,
    @Inject(MAT_DIALOG_DATA) public data:TicketData,
  ){}

  onNoClick(){
    this.dialogRef.close();
  }
}


export const GRID_NAME = [
  {name: 'TO DO ISSUES', content: 'BLAH BLAH BLAH'},
  {name: 'IN PROGRESS', content: 'BLAH BLAH BLAH'},
  {name: 'DONE', content: 'BLAH BLAH BLAH'},
  {name: 'BACKLOG', content: 'BLAH BLAH BLAH'},
]
