import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import { Http, Headers } from '@angular/http';
import { FirebaseApp } from 'angularfire2'; // for methods
import { AngularFireAuth } from 'angularfire2/auth';
import { Jersey, UniformStyle, Ifile,FileObj } from '../app/admin/models/upload'
import * as firebase from 'firebase/app';
import 'rxjs/add/operator/map';

@Injectable()
export class UploadService {
  constructor(private fb: FirebaseApp, private db: AngularFireDatabase) {
    console.log("Upload service started");
  }

  basePath: string = '/jersey-styles';
  uploadJersey: any;

  uploads: FirebaseListObservable<any[]>;
  //takes in an upload object and folder name
  saveNewStyle(newJersey: UniformStyle) {
debugger

    let storageRef = firebase.storage().ref();
    let ref = storageRef.child(`${this.basePath}/${newJersey.name}`)
    var dbRef = this.db.object(`${this.basePath}/${newJersey.name}/`);

    let self=this;

    Object.keys(newJersey).map(function (key, index) {

      if (key == "files") 

    });
  }

  apiHit(newJersey:UniformStyle,index,key)  {

    debugger
    let storageRef = firebase.storage().ref();
    let ref = storageRef.child(`${this.basePath}/${newJersey.name}`)
    var dbRef = this.db.object(`${this.basePath}/${newJersey.name}/`);

    if(index>=0)
    {

      let uploadTask1 = storageRef.child(`${'/jersey-styles'}/${newJersey.name}/${newJersey[key][index].img_url.name}`).put(newJersey[key][index].img_url);

      uploadTask1.on(firebase.storage.TaskEvent.STATE_CHANGED,
        (snapshot) => {

          // upload in progress
          newJersey.progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
        },
        (error) => {
          // upload failed
          console.log(error)
        },
        () => {

          // upload success
          var downloadPath = uploadTask1.snapshot.downloadURL;
          //console.log(uploadTask.snapshot);
          //console.log(uploadTask.snapshot.downloadURL);

          delete newJersey.files[index].img_url;

          newJersey.files[index].img_url = downloadPath;

          dbRef.set(newJersey);
        //  index=index-1;
         // this.apiHit(newJersey,index,key)
        }
      );
    }
  }

  saveFileData(newJersey: any) {
debugger
    this.db.list(`${this.basePath}`).push(newJersey);
  }

  //   deleteUpload(upload: Upload) {
  //    this.deleteFileData(upload.$key)
  //    .then( () => {
  //      this.deleteFileStorage(upload.name)
  //    })
  //    .catch(error => console.log(error))
  //  }
  // Deletes the file details from the realtime db
  private deleteFileData(key: string) {
    return this.db.list(`${this.basePath}/`).remove(key);
  }
  // Firebase files must have unique names in their respective storage dir
  // So the name serves as a unique key
  private deleteFileStorage(name: string) {
    let storageRef = firebase.storage().ref();
    storageRef.child(`${this.basePath}/${name}`).delete()
  }


}

{
        console.log("About to upload")
        console.log(newJersey[key]);

       for (var index = 0; index < newJersey.files.length; index++) {
        //var index=newJersey.files.length;
        self.apiHit(newJersey,index,key)
        }
      }