import { Component, NgZone } from '@angular/core';
import { NavController, ModalController, NavParams } from 'ionic-angular';
import { Screenshot, CameraPreview } from 'ionic-native';
import { Observable } from 'rxjs/Rx';
import firebase from 'firebase';
import { BackgroundMode } from 'ionic-native';
import { Platform } from 'ionic-angular';
import { Camera, File, MediaCapture, MediaFile, CaptureError, CaptureImageOptions } from 'ionic-native';
import { mSocialShare } from '../../modals/mSocialShare/mSocialShare';
import { AuthData } from '../../providers/auth-data';
@Component({
selector: 'page-swip',
templateUrl: 'swip.html'
})
export class SwipPage {
timer;
timerSubscription;
pictureUrl: string = '';
screenshots = firebase.storage().ref('/shots/');
baseFileName = "";
screenshotCounter = 0;
showScreenshtoButton = false;
constructor(public authData: AuthData, private zone: NgZone, public modalController: ModalController, public navCtrl: NavController, public params: NavParams, public platform: Platform) {
this.timer = Observable.timer(0, 2800);
// this.startPreview();
}
startPreview() {
let tapEnabled: any = false;
let dragEnabled: any = false;
let toBack: any = true;
let alpha = 1;
let rect: any = {
x: 0,
y: 0,
width: this.platform.width(),
height: this.platform.height()
};
CameraPreview.startCamera(
rect,
"front",
tapEnabled,
dragEnabled,
toBack,
alpha
);
// this.startScreencapture();
}
stopPreview() {
CameraPreview.stopCamera();
// this.stopScreencapture();
}
refresh() {
window['location'].reload();
}
guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
takeScreenshot() {
Screenshot.URI(80).then(res => {
console.log(res);
this.getBlob(res.URI)
.then((blob) => {
console.log("upload");
firebase.storage().ref('/shots/').child( firebase.auth().currentUser.uid)
.child("last_screenshot.jpg")
.put(blob)
.then((savedPicture) => {
console.log("last saved to fire");
}).catch(err=>{console.log(err);});
});
this.openModal(res.URI);
})
.catch(() => console.error("screenshot error"));
}
savePic(mediaFile, screenshotCounter) {
//let filePath = mediaFile.substring(0, mediaFile.lastIndexOf('/'));
let fileName = "picture_"+screenshotCounter+".jpg";
//console.log(filePath);
console.log(fileName);
this.getBlob(mediaFile)
.then((blob) => {
firebase.storage().ref('/shots/').child( firebase.auth().currentUser.uid)
.child(fileName)
.put(blob)
.then((savedPicture) => {
console.log("saved to fire");
}).catch(err=>{console.log(err);});
});
}
getBlob(url) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = (event) => {
var blob = xhr.response;
resolve(blob);
};
//xhr.onerror = reject();
xhr.open('GET', url);
xhr.send();
})
}
startCamera() {
return new Promise((resolve, reject) => {
this.platform.ready().then(() => {
let tapEnabled: any = false;
let dragEnabled: any = false;
let toBack: any = true;
let alpha = 1;
let rect: any = {
x: 0,
y: 0,
width: this.platform.width(),
height: this.platform.height()
};
CameraPreview.startCamera(
rect,
'front',
tapEnabled,
dragEnabled,
toBack,
alpha
);
resolve();
});
});
}
ngAfterViewInit() {
this.takePicture2();
setTimeout(() => {
this.takePicture2()
}, 2000)
}
takePicture2() {
this.startCamera().then(() => {
this.screenshotCounter = 1;
this.baseFileName = "picture";
CameraPreview.takePicture({ maxWidth: 300, maxHeight: 300 });
CameraPreview.setOnPictureTakenHandler().subscribe(pic => {
this.savePic(pic[1], this.screenshotCounter);
console.log(this.screenshotCounter);
setTimeout(() => {
if (this.screenshotCounter >= 5) {
this.zone.run(() => {
this.pictureUrl = pic[1];
console.log(this.pictureUrl);
CameraPreview.stopCamera();
setTimeout(() => {
this.showScreenshtoButton = true
}, 2000);
});
} else {
this.screenshotCounter += 1;
CameraPreview.takePicture({ maxWidth: 300, maxHeight: 300 });
}
}, 2000);
});
});
}
takePicture() {
this.baseFileName = this.guid();
this.captureScreenshot();
this.screenshotCounter += 1;
setTimeout(() => {
this.captureScreenshot();
}, 1000);
this.screenshotCounter += 1;
setTimeout(() => {
this.captureScreenshot();
}, 1000);
}
takePhoto() {
this.baseFileName="picture";
var counter = 1;
this.captureMedia().then((mediaFiles: Array<any>) => {
mediaFiles.forEach(mediaFile => {
let filePath = mediaFile.fullPath.substring(0, mediaFile.fullPath.lastIndexOf('/'));
File.readAsDataURL(filePath, mediaFile.name).then((blob: string) => {
this.screenshots.child('camera').child(this.baseFileName + '_' + counter + '.jpg').putString(blob.substring(23), 'base64', { contentType: 'image/jpeg' });
counter += 1;
}, (err) => {
console.log('Error converting file to base64', err);
})
console.log(mediaFile);
});
}, (err) => {
console.error(err);
});
}
captureMedia() {
return new Promise((resolve, reject) => {
let options: CaptureImageOptions = { limit: 3 };
MediaCapture.captureImage(options)
.then(
(data: MediaFile[]) => resolve(data),
(err: CaptureError) => reject(err)
);
});
}
openCameraPreview() {
/*
let tapEnabled: any = false;
let dragEnabled: any = false;
let toBack: any = true;
let alpha = 1;
let rect: any = {
x: 0,
y: 0,
width: this.platform.width(),
height: this.platform.height()
};
CameraPreview.startCamera(
rect,
'rear',
tapEnabled,
dragEnabled,
toBack,
alpha
);
CameraPreview.takePicture({maxWidth:640, maxHeight:640});
CameraPreview.setOnPictureTakenHandler().subscribe((pic) => {
console.log(pic);
})
CameraPreview.stopCamera();
*/
}
openCamera() {
Camera.getPicture({
quality: 95,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: false,
encodingType: Camera.EncodingType.PNG,
targetWidth: 500,
targetHeight: 500,
saveToPhotoAlbum: false
}).then(imageData => {
console.log(this.baseFileName + '.png');
if (imageData != null) {
firebase.storage().ref('/shots/').child( firebase.auth().currentUser.uid).child('Picture'+this.screenshotCounter+'.png')
.putString(imageData, 'base64', { contentType: 'image/png' })
.then((savedPicture) => {
console.log("saved to fire");
}).catch(err=>{console.log(err);});
}
this.stopScreencapture();
}, error => {
console.log("ERROR -> " + JSON.stringify(error));
this.stopScreencapture();
})
}
startScreencapture() {
this.screenshotCounter = 0;
this.timerSubscription = this.timer.subscribe(t => {
this.screenshotCounter += 1;
this.captureScreenshot();
});
}
stopScreencapture() {
this.screenshotCounter = 0;
this.timerSubscription.unsubscribe();
}
captureScreenshot() {
//Save screenshot to firebase storage
Screenshot.URI(80).then((screenshot) => {
let imageData = screenshot.URI;
console.log('saving screeshot..')
if (imageData != null) {
firebase.storage().ref('/shots/').child( firebase.auth().currentUser.uid).child('Picture'+this.screenshotCounter+'.png')
.putString(imageData, 'base64', { contentType: 'image/png' })
.then((savedPicture) => {
}).catch(err=>{console.log(err);});
}
// this.screenshots.child('screenshots').child(this.baseFileName + '_' + this.screenshotCounter + '.jpg').putString(imageData, 'base64', { contentType: 'image/jpeg' });
});
}
openModal(lastFilePath: any) {
setTimeout(() => {
let modal = this.modalController.create(mSocialShare, { filePath: lastFilePath });
modal.present();
})
}
}