import {Injectable} from '@angular/core';
import {File} from './file';
import {Observable, of} from 'rxjs';
import {HttpClient} from '@angular/common/http';
import { User } from './user';


@Injectable({
  providedIn: 'root'
})
export class FileService {

  saveUrl = 'http://localhost/sfcode/backend/filesave.php';
  uploadUrl = 'http://localhost/sfcode/backend/fileupload.php';
  fileListUrl = 'http://localhost/sfcode/backend/dir_tree.php';
  deleteUrl = 'http://localhost/sfcode/backend/filedelete.php';
  fileContentUrl = 'http://localhost/sfcode/backend/get_file.php';
  createDirUrl = 'http://localhost/sfcode/backend/newdir.php';

  constructor(private http: HttpClient) {
  }

  getFiles(): Observable<File[]> {

    const ret: File[] = [];
    const arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    for (const item of arr) {
      ret.push({
        username: '',
        filename: 'lambda',
        language: '.cpp',
        text: 'Random Shit',
        path: '/'
      });
    }

    return of(ret);
  }

  upload(file: File, isAttempt: boolean): Observable<any> {
    return this.http.post(this.saveUrl, {file, isAttempt});
  }

  upload2(file): Observable<any> {
    const formData = new FormData();
    formData.append('file', file, file.name);
    return this.http.post(this.uploadUrl, formData);
  }

  delete(file: any, isFile: boolean, username: string, nFiles: number): Observable<any> {
    return this.http.post(this.deleteUrl, {file, isFile, username, nFiles});
  }

  getFileList(username: string): Observable<any> {
    return this.http.post(this.fileListUrl, {username});
  }

  getFileContent(username: string, filepath: string): Observable<any> {
    return this.http.post(this.fileContentUrl, {username, file_path: filepath});
  }

  createDirectory(username: string, dirname: string, path: string): Observable<any> {
    console.log(username, dirname, path);
    return this.http.post(this.createDirUrl, {username, dirname, path});
  }

}
